2017-10-12 56 views
0

我想查找數組內容與索引的組合。此外,與動態組合長度。現在我可以結合這個沒有返回索引:Python Itertools組合

print("Combination result: ") 
for L in range(1, len(splitword)+1): 
    comb = combinations(splitword, L) 
    for combine in comb: 
     print(combine) 

我怎樣才能返回索引與組合?

謝謝

回答

0

改爲使用combinations(range(len(splitword)), L)找到索引。然後從那裏找到值是簡單的索引。

print("Combination result: ") 
for L in range(1, len(splitword)+1): 
    comb = itertools.combinations(range(len(splitword)), L) 
    for combination_index in comb: 
     print(combination_index, [splitword[i] for i in combination_index]) 
+0

哇,太棒了!謝謝,我現在正在學習你的代碼,我是itertools的初學者,你能解釋一下上面的事情嗎? –

+0

我所做的與「itertools」無關。我不是在你的字符串中生成字母的組合,而是隻是對「範圍」進行混洗,即從0到「len(splitword)」的數字。請注意,這相當於重新排列指數,而不是數值本身。 – polwel