2017-11-11 92 views
2

我使用python 2.7我有這樣的名單:從列表中選擇獲取所有組合和值

new_out_filename = ['OFF_B8', 0, 'ON_B8', 1, 'ON_B16', 4, 'OFF_B0', 7] 

我想要得到的字符串的所有組合像OFF_B8_vs_ON_B8OFF_B8_vs_ON_B16OFF_B8_vs_OFf_B0ON_B8_vs_ON_16

有沒有簡單的方法來實現它?

我想是這樣的:

for k in range(0, len(new_out_filename), 2): 
    combination = new_out_filename[k]+'_vs_'+new_out_filename[k+2] 
    print combination 

但我的名單已經出來了指數的,也是我沒有得到相應的結果。

你能幫助我嗎?

+0

在你的例子看到,當k達到了new_out_filename 6個你的程序搜索[8]這將導致出指數 –

+0

的@NimishBansal是的,你是對的。然而,我的代碼解決方案並不是我正在尋找的。 – zinon

+0

你可以從itertools導入組合中瞭解到 –

回答

5

只使用combinations切片名單上忽略數字:

import itertools 
new_out_filename = ['OFF_B8', 0, 'ON_B8', 1, 'ON_B16', 4, 'OFF_B0', 7] 
for a,b in itertools.combinations(new_out_filename[::2],2): 
    print("{}_vs_{}".format(a,b)) 

結果:

OFF_B8_vs_ON_B8 
OFF_B8_vs_ON_B16 
OFF_B8_vs_OFF_B0 
ON_B8_vs_ON_B16 
ON_B8_vs_OFF_B0 
ON_B16_vs_OFF_B0 

或理解:

result = ["{}_vs_{}".format(*c) for c in itertools.combinations(new_out_filename[::2],2)] 

結果:

['OFF_B8_vs_ON_B8', 'OFF_B8_vs_ON_B16', 'OFF_B8_vs_OFF_B0', 'ON_B8_vs_ON_B16', 'ON_B8_vs_OFF_B0', 'ON_B16_vs_OFF_B0'] 
+0

是的,就是這個:) –

+0

太棒了!非常感謝你!這就是我一直在尋找的! – zinon

1

我剛剛添加了額外的循環,它工作。

new_out_filename = ['OFF_B8', 0, 'ON_B8', 1, 'ON_B16', 4, 'OFF_B0', 7] 
for k in range(0, len(new_out_filename), 2): 
    sd = new_out_filename[k+2:] #it will slice the element of new_out_filename from start in the multiple of 2 
    for j in range(0, len(sd), 2): 
     combination = new_out_filename[k]+'_vs_'+sd[j] 
     print (combination) 

輸出:

OFF_B8_vs_ON_B8

OFF_B8_vs_ON_B16

OFF_B8_vs_OFF_B0

ON_B8_vs_ON_B16

ON_B8_vs_OFF_B0

ON_B16_vs_OFF_B0

+0

不要只是發佈代碼。解釋問題是什麼以及你的代碼如何修復它。 – Barmar

+0

好吧,等待我添加評論,並感謝告訴我@Barmar –

相關問題