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

问题描述 投票:0回答:3

我有一个列表,我想获取列表中所有内容的组合。但是,当使用两个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循环执行此操作时,它为我提供了重复的组合。水果= ['苹果','橙色','梨','葡萄'] ...

python for-loop if-statement
3个回答
1
投票

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


0
投票
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)

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.