如何查看元素中出现了多少个列表

时间:2019-05-14 15:10:37

标签: python list loops iteration

我有一些列表:

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:

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

2 个答案:

答案 0 :(得分:0)

最简单甚至是最清晰的方法是执行以下操作:

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")

答案 1 :(得分:0)

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

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