3位数列表的所有可能组合永远不会是sam

2024-04-23 21:35:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个清单,看起来像:

A
B
C
D
E
F
G

我怎么解决这个问题,找到3位数的所有组合。同一个字母不能在同一行中使用。在

^{pr2}$

例如……:

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'

Tags: inimportfor字母rangelistaaprint
3条回答

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

# 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))

输出

^{pr2}$

或者作为一条直线:

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

Python标准库itertools已经具有您正在尝试实现的功能。你还在你的代码中使用它(有趣)。在

itertools.combinations(a,3)返回a的所有3个组合。要将其转换为“list of list”,您应该使用.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)

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.)

相关问题 更多 >