繁体   English   中英

列表的3位数字的所有可能组合永远都不相同

[英]All possible combinations for 3 digits of list never the same

我有一个看起来像这样的列表:

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'

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)

另外,建议您搜索“ 组合,排列差异 ”。 从您的问题中我了解到; 排列就是您想要的。 (如果运行我共享的代码,您将容易理解两者之间的区别。)

要了解解决方案的工作原理,请尝试以下操作:

# 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']

组合适用于字符串而不是列表,因此应首先使用以下命令将其转换为字符串: ''.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))

OUTPUT

abc
abd
abe
acd
ace
ade
bcd
bce
bde
cde

还是单线:

[''.join(comb) for comb in combinations(''.join(x), n)]

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM