Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python merge two lists (even/odd elements)

Tags:

python

merge

list

Given two lists, I want to merge them so that all elements from the first list are even-indexed (preserving their order) and all elements from second list are odd-indexed (also preserving their order). Example below:

x = [0,1,2]
y = [3,4]

result = [0,3,1,4,2]

I can do it using for loop. But I guess there could be a fancy pythonic way of doing this (using a less-known function or something like that). Is there any better solution that writing a for-loop?

edit: I was thinking about list comprehensions, but didn't come up with any solution so far.

like image 900
ducin Avatar asked Nov 27 '22 04:11

ducin


2 Answers

Here's something you can use. (Use list(izip_longest(...)) for Py2x)

>>> from itertools import chain
>>> from itertools import zip_longest
>>> list(filter(lambda x: x != '', chain.from_iterable(zip_longest(x, y, fillvalue = ''))))
[0, 3, 1, 4, 2]

This works for arbitrary length lists like follows -

>>> x = [0, 1, 2, 3, 4]
>>> y = [5, 6]
>>> list(filter(lambda x: x != '', chain.from_iterable(zip_longest(x, y, fillvalue = ''))))
[0, 5, 1, 6, 2, 3, 4]

Explanation on it's working -

  1. zip_longest(...) with a fill value zips the lists and fills in the given fill value for iterables of unequal length. So, for your original example, it evaluates to something like [(0, 3), (1, 4), (2, '')]
  2. We need to flatten the result because this method gives us a list of tuples. For that we use chain.from_iterable(...) giving us something like [0, 3, 1, 4, 2, ''].
  3. We now use filter(...) to remove all occurences of '' and we get the required answer.
like image 87
Sukrit Kalra Avatar answered Nov 29 '22 19:11

Sukrit Kalra


You can simply do:

for i,v in enumerate(y):
    x.insert(2*i+1,v)

this takes the advantage that insert will use the last index when it is overpassed.

One example:

x = [0,1,2,3,4,5]
y = [100, 11,22,33,44,55,66,77]
print x
# [0, 100, 1, 11, 2, 22, 3, 33, 4, 44, 5, 55, 66, 77]
like image 24
Saullo G. P. Castro Avatar answered Nov 29 '22 18:11

Saullo G. P. Castro