繁体   English   中英

在两个“for”循环中遍历列表时如何摆脱重复的组合?

[英]How to get rid of duplicate combinations when going through list in two “for” loops?

我有一个列表,我想获得列表中所有内容的组合。 但是,当使用两个 for 循环来执行此操作时,它给了我重复的组合。

fruits = ['apple', 'orange', 'pear', 'grape']
for x in fruits:
    for y in fruits :
        if x != y:
            print(x, y)

我得到

apple orange
apple pear
apple grape
orange apple
orange pear
orange grape
pear apple
pear orange
pear grape
grape apple
grape orange
grape pear

我不想要的是两者

 apple orange
 orange apple

我想要的只是其中一种组合。

apple orange
apple pear
apple grape
orange pear
orange grape
pear grape

有没有办法使用if语句或在for循环中做到这一点?

您正在寻找的是所有组合(大小为 2),但您正在打印排列(大小为 2)。 您可以为此使用itertools.combinations

from itertools import combinations

fruits = ['apple', 'orange', 'pear', 'grape']
for x in combinations(fruits, 2):
    print(x)

编辑:

你可以用这样for循环来做到这一点:

for i in range(len(fruits)):
    for j in range(i + 1, len(fruits)):
        print(fruits[i], fruits[j])
ans = []
fruits = ['apple', 'orange', 'pear', 'grape']
for x in fruits:
    for y in fruits :
        if x != y and (y, x) not in ans:
            ans.append((x,y))
print(ans)

Output:

[('apple', 'orange'), ('apple', 'pear'), ('apple', 'grape'), ('orange', 'pear'), ('orange', 'grape'), ('pear', 'grape')]

一种有趣的方式,只是让您知道 itertools.product 的用法

from itertools import product
fruits = ['apple', 'orange', 'pear', 'grape']
ans=set()
for x,y in product(fruits,repeat=2):
    if x!=y and (y,x) not in ans:
        ans.add((x,y))
print(ans)

基本原则与 Andrew White 的答案相同,但由于我没有评论权限,我将添加一个单独的答案。 这里的要点是使用集合而不是列表,正如答案所暗示的那样,集合中的“in”(成员关系)具有平均案例常数时间复杂度,其中与列表一样,它是线性的,并且都默认为 O(n)最坏的情况下。

您可以使用一组 freezesets 进行查找:

fruits = ['apple', 'orange', 'pear', 'grape']
lookup = set()

for x in fruits:
    for y in fruits:
        combo = frozenset([x, y])
        if x != y and combo not in lookup:
            lookup.add(combo)
            print(x, y)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM