Home > Blockchain >  How do you sandwich lists together efficiently in python?
How do you sandwich lists together efficiently in python?

Time:11-29

Let's say that I have three lists like this:

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

and instead of concatenating them normally, I want to sandwich them as if they were three different stacks of bingo balls, and I want to take one ball from each stack sequentially.

instead of getting a list of [1,2,3,4,5,6,7,8,9], I would want to end with a list that looks more like this:

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

The easy logic is to take the first number from each list, append it to a new list, and then delete the number from the old list and repeat iteratively through the list of lists. This will work fine, but is painfully slow.

Are there any other options?

CodePudding user response:

When lists are equal length, this is a zip-splat list comprehension:

>>> [n for splat in zip(*list_of_lists) for n in splat]
[1, 4, 7, 2, 5, 8, 3, 6, 9]

Should you need to handle lists of unequal length, what you're describing is essentially the roundrobin recipe shown in the itertools documentation.

CodePudding user response:

Use zip to group by index in the list.

list_of_lists = [ [1,2,3], [4,5,6], [7,8,9] ]
grouped = list(zip(*list_of_lists))
# [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

Then flatten it.

import functools
import operator
functools.reduce(operator.iconcat, grouped, [])
# [1, 4, 7, 2, 5, 8, 3, 6, 9]

For more ways to flatten a list - check out this answer

CodePudding user response:

You can use numpy:

sandwiched_list = np.array(list_of_lists).flatten('F').tolist()
#[1, 4, 7, 2, 5, 8, 3, 6, 9]
  • Related