列表的3位数字的所有可能组合永远都不相同 [英] All possible combinations for 3 digits of list never the same
问题描述
我有一个看起来像这样的列表:
I have a list that looks like:
A
B
C
D
E
F
G
如何解决此问题以找到3位数字的所有组合.同一字母不能在同一行中使用.
How do I solve this to find all combinations for 3 digits. The same letter cannot be used in same row.
ABC
ABD
ABE
ABF
ABG
AGB
例如类似...:
x = ['a','b','c','d','e']
n = 3
import itertools
aa = [list(comb) for i in range(1, n+2) for comb in itertools.combinations(x, i)]
print(aa)
这没有提供所需的输入:
This does not give desired input:
[['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c'
推荐答案
The Python Standard Library itertools already has the functionality you are trying to implement. Also you are using it in your code (funnily).
itertools.combinations(a,3)
返回a的所有3个组合.要将其转换为列表列表",您应按以下方式使用.extend()
;
itertools.combinations(a,3)
returns all 3-combinations of the a. To convert that to "list of list" you should use .extend()
as follows;
x = ['a','b','c','d','e']
n = 3
import itertools
permutations = []
combinations = []
combinations.extend(itertools.combinations(x,n))
permutations.extend(itertools.permutations(x,n))
print("Permutations;", permutations)
print("\n")
print("Combinations;", combinations)
此外,建议您搜索"组合,排列差异 ".从您的问题中我了解到;排列就是您想要的. (如果运行我共享的代码,您将容易理解它们之间的区别.)
Additionally, I suggest you to search on "Combination, Permutation Difference". As I understood from your question; permutation is what you want. (If you run the code I shared, you will understand the difference easliy.)
这篇关于列表的3位数字的所有可能组合永远都不相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!