簡體   English   中英

從列表值獲取所有組合

[英]Get all combinations from list values

我正在使用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

但是我的列表沒有索引,而且我也沒有得到適當的結果。

你能幫我嗎?

只需在切片列表上使用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']

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM