zinon
zinon

Reputation: 4664

Get all combinations from list values

I'm using python 2.7 and I have this list:

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

I want to get all the combinations of the strings like OFF_B8_vs_ON_B8, OFF_B8_vs_ON_B16, OFF_B8_vs_OFf_B0, ON_B8_vs_ON_16, etc.

Is there an easy way to achieve it?

I tried something like:

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

But my list is out of index and also I don't get the appropriate result.

Can you help me please?

Upvotes: 2

Views: 68

Answers (2)

sachin dubey
sachin dubey

Reputation: 779

I just added extra for loop and it is working.

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)

output:

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

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140286

just use combinations on a sliced list to ignore the numbers:

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))

result:

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

or with comprehension:

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

result:

['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']

Upvotes: 5

Related Questions