-1

I am a newbie user of Python. I have four lists of numbers. I would like to create a list that grabs each element from list A and B and pairs them up with every single element in lists C and D.

A=[1,2,3,4]
B=[10,20,30,40]
C=[100,200]
D=[1000,2000]

My desired output is:

1,10,100,1000
1,10,200,2000
2,20,100,1000
2,20,200,2000
3,30,100,1000
3,30,200,2000
4,40,100,1000
4,40,200,2000
Johnny Lastre
  • 81
  • 1
  • 5
  • Please note duplicate is not correct - sorry. See this one http://stackoverflow.com/questions/1663807/how-can-i-iterate-through-two-lists-in-parallel-in-python?lq=1 – YXD Apr 26 '15 at 22:08
  • @MrE I think it's not duplicate. It doesn't need just two zips. It's more than that I believe. – JuniorCompressor Apr 26 '15 at 22:12
  • 1
    For input this simple, you can do it with a comprehension: `result = [i + j for i in zip(A, B) for j in zip(C, D)]`. That gives you a list of tuples that you can work with as needed. – paidhima Apr 26 '15 at 22:14
  • @paidhima Ok very succinct and beautiful :) Little too closer to only two zips. But also needs combination of other things. – JuniorCompressor Apr 26 '15 at 22:17
  • can be done using `for i in range(0, len(A)): for j in range(0, len(C)): print(A[i], B[i], C[j], D[j])` – Niranjan M.R Apr 27 '15 at 00:21
  • @MrE, question is not a duplicate. Both links you posted are asking somewhat different things. Check desired output... – Johnny Lastre Apr 27 '15 at 01:41
  • @JohnnyLastre sorry about this – YXD Apr 27 '15 at 20:49

2 Answers2

5

You can use a combination of product and zip and chain:

A = [1, 2, 3, 4]
B = [10, 20, 30, 40]
C = [100, 200]
D = [1000, 2000]

from itertools import product, chain
for row in product(zip(A, B), zip(C, D)):
    print list(chain(*row))

Result:

[1, 10, 100, 1000]
[1, 10, 200, 2000]
[2, 20, 100, 1000]
[2, 20, 200, 2000]
[3, 30, 100, 1000]
[3, 30, 200, 2000]
[4, 40, 100, 1000]
[4, 40, 200, 2000]
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
0

I think you want the different possible combinations of these lists:

from itertools import combinations
for a, b in zip(A, B): 
    print [c for c in combinations([a,b]+C+D, 4)]
a p
  • 3,098
  • 2
  • 24
  • 46