繁体   English   中英

检查索引的列表项是否在另一个列表中

[英]Checking if list item of index exists in another list

我有一个列表,其中包含线的坐标作为数组。 当我使用列表方法时,有些方法行不通。

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)将引发错误。 如果将它们都注释掉,则将进入“行存在”打印语句:

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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM