Python 检查索引的列表项是否存在于其他列表中
我有一个列表,其中包含作为数组的线的坐标。当我使用列表方法时,有些有效,有些无效Python 检查索引的列表项是否存在于其他列表中,python,arrays,list,Python,Arrays,List,我有一个列表,其中包含作为数组的线的坐标。当我使用列表方法时,有些有效,有些无效 for line1 in line2: print(line2.index(line1)) # doesn't work print(line2[2]) # works line2.pop(0) # works line2.remove(line1) #
for line1 in line2:
print(line2.index(line1)) # doesn't work
print(line2[2]) # works
line2.pop(0) # works
line2.remove(line1) # doesn't work
if line1 in line2: #doesn't work
print('line exist')
# line2 is shown here because I cannot show it properly else where.
[
array([[696, 188, 696, 0]], dtype=int32),
array([[ 2, 192, 2, 0]], dtype=int32),
array([[460, 192, 460, 0]], dtype=int32),
array([[699, 190, 699, 0]], dtype=int32),
array([[802, 192, 802, 0]], dtype=int32),
array([[462, 180, 462, 0]], dtype=int32)
]
基本上,我想检查名为line2的列表中是否存在一行,如果是,则查找其索引并将其删除。您正在向索引函数传递一个值列表。这就是为什么选择哪一个指数会令人困惑。您需要找到需要从列表中删除的元素的索引
lines_to_remove_indices = []
for i, line1 in enumerate(line2):
if line1.all() in line2: #will work
print('line exist')
lines_to_remove_indices.append(i)
for i, line in enumerate(line2):
if not i in lines_to_remove_indices:
new_list.append(line)
line2.pop(0)
将删除该项,因此line2.remove(line1)
将抛出错误。如果您将它们都注释掉,您将进入“line exist”打印语句:
for line1 in line2:
print(line2.index(line1)) # doesn't work
print(line2[2]) # works
#line2.pop(0) # works
#line2.remove(line1) # doesn't work
if line1 in line2: #doesn't work
print('line exist')
你的代码不可读。请正确缩进。现在检查是否正确。在遍历列表时,不应尝试从列表中删除元素。您的具体用例是什么?这些是
numpy
数组吗?您可能需要deepcopy
,因为您有一个嵌套列表line3
=line2
将同时引用同一对象。如果line2中的line_1:ValueError:包含多个元素的数组的真值不明确。使用a.any()或a.all(),您得到的输出是什么?如果第2行中的第1行.all()将起作用,则看起来是这样的值错误:包含多个元素的数组的真值不明确。如果第2行中的line1.all(),则使用.any()或.all()此行:
只需确保已成功删除第1行即可。评论一下吧。当所有条目都已删除时,您将在末尾看到[]
列表。我已注释掉删除行,以检查第2行中的line.all()是否有效。更成功的方法是使用您要保留的元素创建一个新列表。