Home > Net >  Iterating several lists item by item with Python
Iterating several lists item by item with Python

Time:01-23

Using Python, say I have three lists like this:

list1 = ["ABC","JKL","STU"]
list2 = ["DEF", "MNO", "VWX"]
list3 = ["GHI", "PQR", "YZ0"]

I would like to loop the lists, so that the result would be a list like this:

result = ["ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VWX", "YZ0"]

I can make it work with a simple for-loop:

result = []

for i in range(3):
    result.append(list1[i])
    result.append(list2[i])
    result.append(list3[i])

Because the project I want to use this kind of approach includes much more lists than three, I thought using a bit more sophisticated way. I tried using itertools.chain() function, but it loops each list separately before moving to the next one:

result = []

for i in itertools.chain(list1, list2, list3):
    result.append(i)

Is there a way to make this work with itertools.chain() or with some other function?

CodePudding user response:

use numpy.hstack

import numpy as np

list1 = ["ABC","JKL","STU"]
list2 = ["DEF", "MNO", "VWX"]
list3 = ["GHI", "PQR", "YZ0"]

np.hstack([list1, list2, list3]) 
# -> array(['ABC', 'JKL', 'STU', 'DEF', 'MNO', 'VWX', 'GHI', 'PQR', 'YZ0'], dtype='<U3')

CodePudding user response:

You can try

result = sum((list(e) for e in zip(list1, list2, list3)), [])

not the prettiest way. Still playing around. Problem is, that zip returns tuples and they cannot be summed up directly. Therefore, the extra generator to convert e from tuple to list.

  •  Tags:  
  • Related