簡體   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