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],
    ...
]

请注意list_of_lists[0]match list_of_lists[6],我希望在此示例中匹配。

预期的结果是一个循环,它遍历每个列表对象并将其与所有其他对象进行比较,如果有匹配项 - 将其打印出来。

4

1 回答 1

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]
于 2019-08-14T15:46:59.963 回答