[英]Get all combination with n -length from a list
I was wondering how to get all the possible combinations from a list with n-length from python. 我想知道如何从python的n长度列表中获取所有可能的组合。 But there is one catch. 但是有一个陷阱。 It's hard for me to explain as English is not my native language. 我很难解释,因为英语不是我的母语。 So I give an example: 所以我举一个例子:
If I have a list: 如果我有清单:
my_List = [1, 2, 3, 4]
I want it to get an output of with length 3 to be 我希望它获得长度为3的输出为
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 1, 4)
etc etc
But I do NOT want to have repeated lists. 但我不想重复列出。 By that I mean, if I already have 我的意思是,如果我已经有
(1, 1, 2)
I do not have any need for 我不需要
(1, 2, 1) and
(2, 1, 1)
Does that make any sence? 这有什么意义吗? Any help woudl be much apreciated 任何帮助都会被重视
Use itertools.combinations_with_replacement
: 使用itertools.combinations_with_replacement
:
>>> import itertools
>>> my_List = [1, 2, 3, 4]
>>> for xs in itertools.combinations_with_replacement(my_List, 3):
... print(xs)
...
(1, 1, 1)
(1, 1, 2)
(1, 1, 3)
(1, 1, 4)
(1, 2, 2)
(1, 2, 3)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.