0

I have 2 lists of the same size.

list1 = [start1,start2,start3, start4]
list2 = [end1, end2, end3, end4]

startn in list1 corresponds to endn in list2.

I want to use both the lists in a single for loop for further calculations. Problem being: I want to use a combination of 2 elements from each list in the for loop. For example: I want to extract start1, start3 from list1 and end1, end3 from list2 and use these 4 values in a for loop.

For a single list, to extract a combination of 2 elements, I know it's the following code:

import itertools
for a, b in itertools.combinations(mylist, 2):    

But how do I extract 2 values from list1 and the same corresponding values from list2 and use in a for loop?

Ivan A.
  • 409
  • 3
  • 9
user3535492
  • 87
  • 1
  • 1
  • 6

3 Answers3

4

You can zip the two lists and then use combination to pull out the values:

list1 = ['a', 'b', 'c', 'd']
list2 = [1,2,3,4]

from itertools import combinations
for x1, x2 in combinations(zip(list1, list2), 2):
    print(x1, x2)

#(('a', 1), ('b', 2))
#(('a', 1), ('c', 3))
#(('a', 1), ('d', 4))
#(('b', 2), ('c', 3))
#(('b', 2), ('d', 4))
#(('c', 3), ('d', 4))
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

There's probably a more Pythonic way but try this:

from itertools import combinations

for i, j in combinations(range(4), 2):
    list1_1, list1_2, list2_1, list2_2 = list1[i], list1[j], list2[i], list2[j]

Edit: on second thoughts this is the Pythonic way. I see other people have the same idea though.

for (list1_1, list1_2), (list2_1, list2_2) in combinations(zip(list1, list2), 2):
Denziloe
  • 7,473
  • 3
  • 24
  • 34
0

Use zip to combine the start and end lists together into a bunch of tuples: (s1, e1), (s2, e2), etc. Then do combinations of that:

import itertools

starts = 'start1 start2 start3 start4'.split()
ends   = 'end1 end2 end3 end4'.split()

se_pairs = zip(starts, ends)

for a,b in itertools.combinations(se_pairs, 2):
    a_start, a_end = a
    b_start, b_end = b

    print("a: (", a_start, ",", a_end, ")", "b: (", b_start, ",", b_end, ")")
aghast
  • 14,785
  • 3
  • 24
  • 56