python - Itertools 排列

标签 python python-3.x python-itertools

我有一个列表 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/

相关文章:

python - webapp2 - 只读文件系统错误

python - 如何在 python 中使用 os.path.getsize() 和 * ?

python - 以 t 开头但以 e 以外的其他词结尾的单词

python - 如何在 Python 3 中使用过滤器、映射和归约

python - 生成大小为 n 的二进制数作为元组 : itertools. Product(*[(0, 1)] * n)

python - Python 中的 "Slice lists"和 "the ellipsis";切片列表和带有切片列表的列表列表

python - 转密和放大镜代码

python - matplotlib 中的密度图(热图)

json - 自定义文件名以在PySpark中写入数据框

python - 为什么文档提到 padnone 模拟内置 map 的行为?