Andy
Andy

Reputation: 23

python-2.7 .zip multiple generated lists

Lets say I have a function that generates X amount of equal length lists based on function call. e.g if there are 5 separate strings in function call it should generate 5 lists and .zip/join/merge them into one.

To accomplish this i am using this mockup function:

def FetchData(*args):
   returnlist = []
   for arg in args:
      datalist = generate.list(arg) #obviously not a real method.

      if returnlist == []
          returnlist = datalist 
      else:
          returnlist = map(list, zip(returnlist, datalist))

    return returnlist

This works fine if there are 0, 1 or 2 arguments. However, IF there are more, things get weird:

Here is a sample result when FetchData() gets 4 arguments:

>>> returnlist[0]
>>> [[['a', 'b'], 'c'], 'd']

But i need:

>>> ['a','b','c','d']

I sorta fixed it by 'strigifying' each returnlist item and removing extra symbols, but that seems way too crude.

I am sure there is a way to properly .zip the generated lists without the need to comprehend the result afterwards.

Can anyone help?

Upvotes: 2

Views: 2259

Answers (1)

Jon Clements
Jon Clements

Reputation: 142226

How about the following:

from itertools import chain
def fetch_data(*args):
    return list(chain.from_iterable(zip(*args)))

a = [ [1,2,3], [4,5,6], [7, 8, 9] ]

print fetch_data(*a)
# [1, 4, 7, 2, 5, 8, 3, 6, 9]

Or, return map(list, zip(*args)) will give you: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Upvotes: 4

Related Questions