我正在使用python 2.7
,我有这个列表:
new_out_filename = ['OFF_B8', 0, 'ON_B8', 1, 'ON_B16', 4, 'OFF_B0', 7]
我希望得到OFF_B8_vs_ON_B8
,OFF_B8_vs_ON_B16
,OFF_B8_vs_OFf_B0
,ON_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 :(得分: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']
答案 1 :(得分:1)
我刚添加额外的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