繁体   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