【问题标题】:How to see how many lists an element appears in如何查看一个元素出现在多少个列表中
【发布时间】:2019-05-14 15:10:37
【问题描述】:

我有几个列表:

one = [[ham, egg], [sausage, bacon]]
two = [[pancake, bacon], [ham, egg]]
three = [[sausage, bacon], [butter, toast]]
four = [[ham, egg], [butter, toast]]

我想做的是能够遍历这些列表,并找到它们之间的共同点。作为一个我想去哪里的想法,我希望得到这样的结果:

One
[ham, egg]
matches with Two
[ham, egg]
matches with Four
[ham, egg]
One
[sausage, bacon]
matches with Three
[sausage, bacon]
Three
[butter, toast]
matches with Four
[butter, toast]

我发现要达到这一点非常复杂。我知道你可以遍历一个列表并将列表元素与其他列表进行比较,但这似乎不是很干净,必须像这样:

for item in one:
    if item in two or three or four:
for item in two:
    if item in one or three or four:

有没有一种方法可以一次将所有列表元素与其他列表进行比较以获得预期结果?

【问题讨论】:

    标签: python list loops iteration


    【解决方案1】:

    这是一个可行的解决方案:

    one = [['ham', 'egg'], ['sausage', 'bacon']]
    two = [['pancake', 'bacon'], ['ham', 'egg']]
    three = [['sausage', 'bacon'], ['butter', 'toast']]
    four = [['ham', 'egg'], ['butter', 'toast']]
    
    lists = [one, two, three, four]
    names = {0: 'one', 1: 'two', 2: 'three', 3: 'four'}
    
    for i in range(len(lists)):
        for j in range(len(lists[i])):
            for k in range(i+1, len(lists)):
                if lists[i][j] in lists[k]:
                    print("{} {} matches with {}".format(names[i], lists[i][j], names[k]))
    

    输出将是:

    one ['ham', 'egg'] matches with two
    one ['ham', 'egg'] matches with four
    one ['sausage', 'bacon'] matches with three
    two ['ham', 'egg'] matches with four
    three ['butter', 'toast'] matches with four
    

    【讨论】:

    • 这会产生我想要的确切输出,非常感谢。 :)
    【解决方案2】:

    最简单也可能是最清晰的方法是这样做:

    mylists = [one, two, three, four]
    
    for i, l in enumerate(mylists):
        for j, other in enumerate(mylists[:i] + mylists[i+1:]):
            for item in l:
                if item in other:
                    print(i, j, item)
    

    如果您确实需要日志中原始列表的名称:

    mylists = {'one': one, 'two': two, 'three': three, 'four': four}
    
    for k1, l1 in mylists.items():
        for k2, l2 in mylists.items():
            if k1 == k2:
                continue
            for item in l1:
                if item in l2:
                    print(f"item {item} from {k1} found in {k2}")
    

    执行此类操作的另一种方法是使用itertools 库:

    for item1, lst2 in itertools.product(one, [two, three, four]):
        if item1 in lst2:
            print(f"{item1} match")
    

    【讨论】:

    • 太棒了,这些都很有帮助,感谢您的回复!
    猜你喜欢
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2023-03-17
    • 2019-06-18
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 2017-03-14
    相关资源
    最近更新 更多