Python 3列出了子元素的比较

时间:2018-05-29 00:27:21

标签: python python-3.x

我有一个包含以下元素的列表

queue = [[(1, 5), 4, (1, 4)], [(2, 2), 6, (2, 3)], 
         [(1, 3), 6, (2, 3)], [(1, 3), 6, (1, 4)]]

另一个叫

neighbors = [[(1, 5), 4, (1, 4)], [(1, 3), 6, (1, 4)], 
             [(2, 4), 4, (1, 4)], [(0, 4), 6, (1, 4)]]

如何检查第二个列表中的第一个元组元素是否存在于第一个?

通常我会这样做:

for item in neighbors:
    if item[0] in queue:
        Do something...

但是缺少了一些东西。

1 个答案:

答案 0 :(得分:1)

建立queue的索引,如:

queue_exists = set(q[0] for q in queue)

然后测试是否在queue中:

if item[0] in queue_exists:

测试代码:

queue = [[(1, 5), 4, (1, 4)], [(2, 2), 6, (2, 3)], [(1, 3), 6, (2, 3)],
         [(1, 3), 6, (1, 4)]]

neighbors = [[(1, 5), 4, (1, 4)], [(1, 3), 6, (1, 4)], [(2, 4), 4, (1, 4)],
             [(0, 4), 6, (1, 4)]]

queue_exists = set(q[0] for q in queue)

for item in neighbors:
    if item[0] in queue_exists:
        print(item)

结果:

[(1, 5), 4, (1, 4)]
[(1, 3), 6, (1, 4)]