首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关于排序的itertools.combinations_with_replacement()

关于排序的itertools.combinations_with_replacement()
EN

Stack Overflow用户
提问于 2017-03-29 21:32:05
回答 1查看 333关注 0票数 0

我需要,给定一个顺序和一个最大,一个列表的所有‘订单’长度列表与每个元素的范围(最大值)。itertools.combinations_with_replacement()不起作用,因为在我想要的例子中,虽然它给出了最多的结果

代码语言:javascript
复制
max, order = 3, 2
[(0,0), (0,1), (0,2), (0,3), (1,0), (1,1), (1,2), (1,3), (2,0), (2,1), (2,2), (2,3), (3,0), (3,1), (3,2), (3,3)]

下面的代码缩短了几个元素

代码语言:javascript
复制
list(itertools.combinations_with_replacement([x for x in range(max+1)], order))

[(0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3)]

具体来说,我需要知道是否有迭代工具或其他包给我上面的第一个列表。也就是说,我需要(0,1)和(1,0)。或者在order=3情况下,(0,0,1) (0,1,0)和(1,0,0)都需要包括在内。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-29 21:36:56

你在找itertools.product

代码语言:javascript
复制
>>> max, order = 3, 2
>>> print(list(itertools.product(range(max + 1), repeat=order)))
[(0, 0), (0, 1), (0, 2), (0, 3),
 (1, 0), (1, 1), (1, 2), (1, 3),
 (2, 0), (2, 1), (2, 2), (2, 3),
 (3, 0), (3, 1), (3, 2), (3, 3)]
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43104514

复制
相关文章

相似问题

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