我有一个列表,我想获取列表中所有内容的组合。但是,当使用两个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
循环内执行此操作的方法?
我有一个列表,我想获取列表中所有内容的组合。但是,当使用两个for循环执行此操作时,它为我提供了重复的组合。水果= ['苹果','橙色','梨','葡萄'] ...
您正在寻找的是所有组合(尺寸2),但您正在打印排列(尺寸2)。您可以为此使用itertools.combinations
:
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)
一种有趣的方式,只是您知道itertools.product的用法