Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Elementwise join of two lists of same length

Tags:

python

I have two lists of the same length

a = [[1,2], [2,3], [3,4]]
b = [[9], [10,11], [12,13,19,20]]

and want to combine them to

c = [[1, 2, 9], [2, 3, 10, 11], [3, 4, 12, 13, 19, 20]]

I do this by

c= []
for i in range(0,len(a)):
    c.append(a[i]+ b[i])

However, I am used from R to avoid for loops and the alternatives like zip and itertools do not generate my desired output. Is there a way to do it better?

EDIT: Thanks for the help! My lists have 300,000 components. The execution time of the solutions are

[a_ + b_ for a_, b_ in zip(a, b)] 
1.59425 seconds
list(map(operator.add, a, b))
2.11901 seconds
like image 629
HOSS_JFL Avatar asked Apr 04 '16 13:04

HOSS_JFL


2 Answers

Python has a built-in zip function, I'm not sure how similar it is to R's, you can use it like this

a_list = [[1,2], [2,3], [3,4]]
b_list = [[9], [10,11], [12,13]]
new_list = [a + b for a, b in zip(a_list, b_list)]

the [ ... for ... in ... ] syntax is called a list comprehension if you want to know more.

like image 131
John Avatar answered Oct 18 '22 02:10

John


>>> help(map)
map(...)
    map(function, sequence[, sequence, ...]) -> list

    Return a list of the results of applying the function to the items of
    the argument sequence(s).  If more than one sequence is given, the
    function is called with an argument list consisting of the corresponding
    item of each sequence, substituting None for missing values when not all
    sequences have the same length.  If the function is None, return a list of
    the items of the sequence (or a list of tuples if more than one sequence).

As you can see, map(…) can take multiple iterables as argument.

>>> import operator
>>> help(operator.add)
add(...)
    add(a, b) -- Same as a + b.

So:

>>> import operator
>>> map(operator.add, a, b)
[[1, 2, 9], [2, 3, 10, 11], [3, 4, 12, 13]]

Please notice that in Python 3 map(…) returns a generator by default. If you need random access or if your want to iterate over the result multiple times, then you have to use list(map(…)).

like image 32
kay Avatar answered Oct 18 '22 00:10

kay