无序的itertools笛卡尔积

4

编辑:user2357112正确标记我的问题为重复。链接的答案适用于我的问题。

我将保留这个问题,因为我认为它与链接的问题措辞不同,可能有助于其他人找到正确的答案。


我想对列表中所有索引之间的排列进行迭代。

例如,对于列表['a','b','c'],我想要迭代索引ij,以便我可以将'a'与'a''b''c'等进行比较。

基本上只需要两个嵌套的for循环,所以itertools中的product非常方便。

但它实际上做了我所需的工作的两倍。我只需要上三角形(i,j)对(因此是无序对——例如,如果遍历(0,1),则不需要(1,0))。

我认为这肯定是一个已经回答过的问题,但我找不到它。您能否帮忙回答或者,如果这是一个重复的问题,指点我正确的方向?谢谢!


我有:

from itertools import product

exList = ['a', 'b', 'c']

for i,j in product(range(len(exList)), range(len(exList))):
    print([i,j])

---
Out:

[0, 0]
[0, 1]
[0, 2]
[1, 0]
[1, 1]
[1, 2]
[2, 0]
[2, 1]
[2, 2]

但我只需要一半的计算量,例如[0,1][1,0]是多余的。

所以itertools的输出是有序对。我想要一个无序对,就像一个三角矩阵。

我的期望输出:

from itertools import product

exList = ['a', 'b', 'c']

helpfulFunction(exList)

---
Out:

[0, 0]
[0, 1]
[0, 2]
[1, 1]
[1, 2]
[2, 2]
2个回答

5

如果j大于或等于i,则使用if语句和过滤器,只有print才能执行:

for i,j in product(range(len(exList)), range(len(exList))):
    if j >= i:
        print([i, j])

更好的方法:

使用 combinations_with_replacement

for i, j in itertools.combinations_with_replacement(range(len(exList)), 2):
    print(i, j)

输出结果均为:

[0, 0]
[0, 1]
[0, 2]
[1, 1]
[1, 2]
[2, 2]

3
如何使用 itertools.combinations_with_replacement
from itertools import combinations_with_replacement
a = ['a', 'b', 'c']
list(combinations_with_replacement(a, 2))
[(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]

这将使您能够做到:
for i, j in combinations_with_replacement(range(len(a)), 2):
   print(i, j)

0 0
0 1
0 2
1 1
1 2
2 2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接