简体   繁体   English

从列表中获取n长度的所有组合

[英]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.

相关问题 从给定的单词列表中生成具有“N”长度的所有可能组合(寻找不重复) - Generate all possible combination with “N” length from given words list (Looking for no repeat) 列出给定长度限制 k 的列表 1 到 n 的所有组合 - Listing all combination of list 1 to n given length restriction k 查找 n 个元素的所有 k 个组合长度 - Find all k combination length of n elements 给定一个数字,生成长度为n的X和O的所有可能组合的列表 - Given a number, generate a list of all possible combination of X and O with length n 从 Python 中长度为 n 的列表中获取 n * k 个唯一的 2 组 - Get n * k unique sets of 2 from list of length n in Python 获取长度为n的所有可能二进制元组的列表 - Get a list of all possible binary tuples with length n 如何获取长度为 n 的所有二进制数的列表? - How to get a list of all binary numbers of length n? 从q个元素的列表创建所有长度为“ n”的列表 - Creating all lists of length “n” from a list of q elements 如何查找大小从 1 到列表长度的列表的所有组合(没有 Itertools) - How to Find All Combination of a List of size from 1 to length of list (Without Itertools) 从列表字母中打印所有可能的长度为 10 的单词的组合,其中重复“A”两次 - Print all possible combination of words of length 10 from a list letters with repeating 'A' exactly twice
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM