Itertools无ord的笛卡尔积

2024-09-30 03:22:15 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:user2357112正确地将我的问题标记为重复。链接的答案适用于我的问题。你知道吗

我不提这个问题,因为我认为这个问题的措辞与相关问题不同,可能有助于其他人找到正确的地方。你知道吗


我想在列表中的所有索引之间进行排列。你知道吗

例如,对于列表['a'、'b'、'c'],我想迭代索引ij,以便比较'a'和'a'、'b'、'c'等

这基本上只是两个嵌套for循环,因此itertools的产品很好地实现了这一点。你知道吗

但它基本上是我需要的两倍。我只需要上三角(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]

Tags: 答案from标记import编辑列表forlen
2条回答

执行if语句并筛选如果j大于或等于i,则仅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]

使用^{}怎么样?你知道吗

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

相关问题 更多 >

    热门问题