简体   繁体   English

如何让Python用固定的有限集中的元素打印给定长度的所有列表?

[英]How can I make Python print all lists of given length with elements in a fixed finite set?

For example, I would like to be able to get all lists of length 5 with elements in the set {0,1,2,3}. 例如,我希望能够获得所有长度为5的列表,其中包含集合{0,1,2,3}中的元素。

I'm sure there is an easy answer but I am stuck and I don't see how to do it! 我敢肯定有一个简单的答案,但是我被困住了,我不知道该怎么做!

You're probably looking for itertools ' combinations_with_replacement : 你可能寻找itertools ' combinations_with_replacement

list(itertools.combinations_with_replacement(range(4),2))
Out[18]: 
[(0, 0),
 (0, 1),
 (0, 2),
 (0, 3),
 (1, 1),
 (1, 2),
 (1, 3),
 (2, 2),
 (2, 3),
 (3, 3)]

(shown for n=2 for brevity) (为简洁起见, n=2

If you don't count (1,2) and (2,1) as distinct, use roippi's answer. 如果您不将(1,2)(2,1)区别开来,请使用roippi的答案。 If you do, itertools.product (as in, "Cartesian product") works here: 如果您这样做,则itertools.product (如“笛卡尔积”中所示)在这里起作用:

>>> import itertools
>>> itertools.product(range(5), repeat=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)]

Do this: 做这个:

import itertools    
list(itertools.product([0,1,2,3], repeat=5))

Combinations_with_replacement will catch all cases. Combinations_with_replacement将捕获所有情况。 It treats (a,b) as the same of (a,b). 它将(a,b)与(a,b)相同。 In practice, it will only output ordered results (ex. (1,3), but not (3,1)) 实际上,它只会输出有序结果(例如(1,3),而不是(3,1))

暂无
暂无

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

相关问题 给定固定样本大小,如何在 python 中打印列表元素? - How to print elements of list in python given a a fixed sample size? 如何生成给定长度和元素总和的所有元组的集合? - How to generate a set of all tuples of given length and sum of elements? 如何在python中将可变长度列表打印为列? - How to print variable length lists as columns in python? 如何创建一个循环使用特定 class 的所有元素并打印找到的所有文本 - How can I make a for loop that loops all elements with a specific class and print all the text found 如何使用 for 循环打印没有每个项目的所有列表,python 中是否有替代方案? - How can I print all lists without each item using for loops, and is there an alternative in python? 检查列表列表的函数具有0到n之间的所有整数元素,并且列表是否都具有给定的长度? - Function to check list of lists have all integer elements between 0 and n and lists are all of given length? 如何在Python 3中的defaultdict中打印所有索引的列表? - How do I print the lists of all the indices within defaultdict in Python 3? 在 Python 中,当元素列表的长度发生变化时,如何循环遍历给定 Xpath 组的所有可点击元素 - In Python, how to loop through all clickable elements of a given Xpath group when length of list of elements changes Python - 所有print和stdout如何从终端获取以便我可以创建日志? - Python - all the print and stdout how can i get from terminal so that i can make a log? 如何通过添加列表来使列表列表中的所有列表具有相同的长度 - How to make all lists in a list of lists the same length by adding to them
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM