Skip to content Skip to sidebar Skip to footer

Python: Elementwise Join Of Two Lists Of Same Length

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]

Solution 1:

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.

Solution 2:

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

    Return a list of the results of applying the functionto the items of
    the argument sequence(s).  If more than one sequence is given, the
    functioniscalledwith an argument list consisting of the corresponding
    item ofeach sequence, substituting Nonefor missing valueswhennotall
    sequences have the same length.  If the functionisNone, 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(…)).

Solution 3:

You can do it this way:

>>> [x+b[i] for i,x in enumerate(a)]
[[1, 2, 9], [2, 3, 10, 11], [3, 4, 12, 13, 19, 20]]

To merge two lists, python makes it so easy:

mergedlist = listone + listtwo

Post a Comment for "Python: Elementwise Join Of Two Lists Of Same Length"