Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group multiple lists into single list in a Pythonic way?

Tags:

python

I've a function returning list from list of lists where the return list groups members of each list by index numbers. Code and example:

def listjoinervar(*lists: list) -> list:
    """returns list of grouped values from each list 
        keyword arguments:
        lists: list of input lists
    """ 
    assert(len(lists) > 0) and (all(len(i) == len(lists[0]) for i in lists))
    joinedlist = [None] * len(lists) * len(lists[0])
    for i in range(0, len(joinedlist), len(lists)):
        for j in range(0, len(lists[0])):
            joinedlist[i//len(lists[0]) + j*len(lists[0])] = lists[i//len(lists[0])][j]
    return joinedlist

a = ['a', 'b', 'c']
b = [1, 2, 3]
c = [True, False, False]
listjoinervar(a, b, c)
# ['a', 1, True, 'b', 2, False, 'c', 3, False]

Are there ways to make this more Pythonic using itertools, generators, etc? I've looked at examples like this but in my code there is no interaction b/w the elements of the individual lists. Thanks

like image 878
shanlodh Avatar asked Dec 21 '25 21:12

shanlodh


1 Answers

Use itertools.chain.from_iterable + zip:

from itertools import chain

def listjoinervar(*a):
    return list(chain.from_iterable(zip(*a)))

Usage:

>>> a = ['a', 'b', 'c']
>>> b = [1, 2, 3]
>>> c = [True, False, False]
>>> listjoinervar(a, b, c)
['a', 1, True, 'b', 2, False, 'c', 3, False]
like image 94
Austin Avatar answered Dec 24 '25 09:12

Austin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!