我有一个列表 x=[1,2,3,4,5],想看看这个列表的不同排列,一次取两个数字。
x=[1,2,3,4,5]
from itertools import permutations
y=list(i for i in permutations(x,2) if i[0]<i[1])
print(y)
输出:[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5) , (3, 4), (3, 5), (4, 5)]
但我还希望输出中包含 [(1,1),(2,2),(3,3),(4,4),(5,5)]
。如何纠正这个问题?
最佳答案
你想要combinations_with_replacement()
相反:
>>> from itertools import combinations_with_replacement
>>> list(combinations_with_replacement(x, 2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5), (5, 5)]
关于python - Itertools 排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47122201/