我有一个包含多个列表对象的列表,我希望将每个内部列表与外部列表对象中的所有其他内部列表进行比较,如果找到匹配项,则将其打印出来。
我已经尝试过遍历列表中的每个对象,并将其与所有其他对象进行比较,但是我总是与开始的对象匹配。
我的示例列表是这样:
list_of_lists = [
[1, 11, 17, 21, 33, 34],
[4, 6, 10, 18, 22, 25],
[1, 15, 20, 22, 23, 31],
[3, 5, 7, 18, 23, 27],
[3, 22, 24, 25, 28, 37],
[7, 11, 12, 25, 28, 31],
[1, 11, 17, 21, 33, 34],
...
]
请注意,list_of_lists[0]
与list_of_lists[6]
相匹配,在此示例中我希望与之匹配。
预期结果是循环遍历每个列表对象,如果有匹配项,则将其与所有其他对象进行比较-将其打印出来。
答案 0 :(得分:0)
您可以执行以下操作:
list_of_lists = [
[1, 11, 17, 21, 33, 34],
[4, 6, 10, 18, 22, 25],
[1, 15, 20, 22, 23, 31],
[3, 5, 7, 18, 23, 27],
[3, 22, 24, 25, 28, 37],
[7, 11, 12, 25, 28, 31],
[1, 11, 17, 21, 33, 34],
]
for i in range(len(list_of_lists)):
for j in range(len(list_of_lists)):
# If you're checking the row against itself, skip it.
if i == j:
break
# Otherwise, if two different lists are matching, print it out.
if list_of_lists[i] == list_of_lists[j]:
print(list_of_lists[i])
这将输出:
[1, 11, 17, 21, 33, 34]