如何解决尝试将列表中仅包含一个 int 的列表转换为列表中的一个 int
我正在尝试创建一种方法来检查列表中是否有任何 1 个数字列表,并将该数字列表转换为一个 int。所以它不再是列表中的列表。
我使用以下代码作为指导,但此代码适用于矩阵,而我的是 3d 列表。
nmap x :r /path/to/file<CR>
这就是我想要做的,但我得到了 indexerror: invalid index to scalar variable:
# Process grid with Possible array values as cells are solved
for row in range(0,GRIDSIZE):
for col in range(0,GRIDSIZE):
# Found correct cell value = Only 1 possible value
if np.size(P[row,col]) == 1:
singleton = P[row][col][0]
grid[row][col] = singleton
# Remove from Possible list
P[row,col].remove(singleton)
对于“从可能的列表中删除”部分,是否有一个简单的 pythonic 命令可以从二维列表中删除该单例元素?
这是目前列表的样子:
解决方法
您可以使用嵌套列表理解:
original_list = [[[7],8,5,[6],1,3,[2,6],[4],9],[6,4,[8,2,7,5],[[1],[1,6]],6,9,1],[9,[1],[7],3],[3,[9],[6]],[5,2],[4,7],[7]],4]]
new_list = [[elem[0] if (isinstance(elem,list) and len(elem)==1) else elem for elem in sublist] for sublist in original_list ]
# new_list
"""
[[7,4]]"""
编辑:使用 for 循环:
new_list = []
for sublist in original_list:
new_sublist = []
for elem in sublist:
if (isinstance(elem,list) and len(elem) == 1):
new_sublist.append(elem[0])
else:
new_sublist.append(elem)
new_list.append(new_sublist)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。