首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Itertools排列

Itertools排列
EN

Stack Overflow用户
提问于 2017-11-05 13:37:42
回答 1查看 365关注 0票数 2

我有一个列表,比如说x=1,2,3,4,5,想看看这个列表的不同排列,一次取两个数字。

代码语言:javascript
复制
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中纠正这一点吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-05 13:45:02

您需要的是combinations_with_replacement(),而不是:

代码语言:javascript
复制
>>> 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)]
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47122201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档