简体   繁体   English

Python-如何生成大小大于列表元素个数的排列

[英]Python - How to generate permutations of size greater than the number of list elements

Sorry if that title made no sense. 抱歉,该标题没有意义。 What I mean is this: I have a list [A, B, C] and I want all possible permutations of those elements that will fill a list of length 10. 我的意思是:我有一个列表[A, B, C] ,我希望这些元素的所有可能排列将填充长度为10的列表。

[A, B, C] => [A, A, A, A, A, A, A, A, A, A]
          => [A, A, A, A, A, A, A, A, A, B]
          ...
          => [C, C, C, C, C, C, C, C, C, C]

I've been reading through the itertools documentation but the permutations function wouldn't work in this case unless the output list length was less than or equal to 3. Thanks! 我一直在阅读itertools文档,但在这种情况下,除非输出列表的长度小于或等于3,否则permutations功能将无法正常工作。谢谢!

You are producing the product of the values, so use itertools.product() with a repeat set: 您正在产生值的乘积 ,因此请使用具有重复集的itertools.product()

from itertools import product

for combo in product(['A', 'B', 'C'], repeat=10):

Demo: 演示:

>>> from itertools import product
>>> products = product(['A', 'B', 'C'], repeat=10)
>>> next(products)
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A')
>>> next(products)
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B')
>>> next(products)
('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'C')
>>> from itertools import islice
>>> skip_to_end = islice(products, (3 ** 10) - 6, None)
>>> next(skip_to_end)
('C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'A')
>>> next(skip_to_end)
('C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'B')
>>> next(skip_to_end)
('C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM