【问题标题】:In a list of list objects, how do i compare each list object with all other list objects?在列表对象列表中,如何将每个列表对象与所有其他列表对象进行比较?
【发布时间】:2019-12-21 03:04:31
【问题描述】:

我有一个包含多个列表对象的列表,我希望将每个内部列表与外部列表对象中的所有其他内部列表进行比较,如果找到匹配项,请将其打印出来。

我已经尝试遍历列表中的每个对象并将其与所有其他对象进行比较,但我总是匹配我开始的那个。

我的示例列表是这样的:

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],我希望在此示例中匹配。

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

【问题讨论】:

标签: python-3.x loops list-comparison


【解决方案1】:

你可以这样做:

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多