我有一个列表,比如说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)]在output.How中纠正这一点吗?
发布于 2017-11-05 13:45:02
您需要的是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)]https://stackoverflow.com/questions/47122201
复制相似问题