我有一个类似的列表:
A
B
C
D
E
F
G
如何解决此问题以查找3位数的所有组合。同一行不能使用相同的字母。
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)
这不会给出所需的输入:
[['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c'
答案 0 :(得分:1)
Python标准库itertools已经具有您尝试实现的功能。你也在你的代码中使用它(有趣)。
itertools.combinations(a,3)
返回a的所有3种组合。要将其转换为“列表列表”,您应使用.extend()
,如下所示;
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)
此外,我建议您搜索“Combination, Permutation Difference”。据我所知,你的问题;排列是你想要的。 (如果你运行我分享的代码,你会理解差异很容易。)
答案 1 :(得分:0)
要了解解决方案流程的工作原理,请尝试以下操作:
# get all combinations of n items from given list
def getCombinations(items, n):
if len(items) < n: return [] # need more items than are remaining
if n == 0: return [''] # need no more items, return the combination of no items
[fst, *rst] = items
# all combinations including the first item in the list
including = [fst + comb for comb in getCombinations(rst, n-1)]
# all combinations excluding the first item in the list
excluding = getCombinations(rst, n)
both = including + excluding
return both
x = ['a','b','c','d','e']
n = 3
print(getCombinations(x, n))
# ['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde', 'cde']
答案 2 :(得分:0)
组合适用于字符串而非列表,因此您应首先使用以下字符将其转换为字符串:''.join(x)
from itertools import combinations
x = ['a', 'b', 'c', 'd', 'e']
n = 3
aa = combinations(''.join(x), n)
for comb in aa:
print(''.join(comb))
<强>输出强>
abc
abd
abe
acd
ace
ade
bcd
bce
bde
cde
或者作为一个单行:
[''.join(comb) for comb in combinations(''.join(x), n)]