我有一个包含以下元素的列表
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...
但是缺少了一些东西。
答案 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)]