简体   繁体   中英

how to merge the values of a list of lists and a list into 1 resulting list of lists

I have a list of lists ( a ) and a list ( b ) which have the same "length" (in this case "4"):

a = [
      [1.0, 2.0],
      [1.1, 2.1],
      [1.2, 2.2],
      [1.3, 2.3]
    ]

b = [3.0, 3.1, 3.2, 3.3]

I would like to merge the values to obtain the following ( c ):

c = [
      [1.0, 2.0, 3.0],
      [1.1, 2.1, 3.1],
      [1.2, 2.2, 3.2],
      [1.3, 2.3, 3.3]
    ]

currently I'm doing the following to achieve it:

c = []
for index, elem in enumerate(a):
    x = [a[index], [b[index]]]  # x assigned here for better readability
    c.append(sum(x, []))

my feeling is that there is an elegant way to do this...
note: the lists are a lot larger, for simplicity I shortened them. they are always(!) of the same length.

In python3.5+ use zip() within a list comprehension and in-place unpacking:

In [7]: [[*j, i] for i, j in zip(b, a)]
Out[7]: [[1.0, 2.0, 3.0], [1.1, 2.1, 3.1], [1.2, 2.2, 3.2], [1.3, 2.3, 3.3]]

In python 2 :

In [8]: [j+[i] for i, j in zip(b, a)]
Out[8]: [[1.0, 2.0, 3.0], [1.1, 2.1, 3.1], [1.2, 2.2, 3.2], [1.3, 2.3, 3.3]]

Or use numpy.column_stack in numpy:

In [16]: import numpy as np
In [17]: np.column_stack((a, b))
Out[17]: 
array([[ 1. ,  2. ,  3. ],
       [ 1.1,  2.1,  3.1],
       [ 1.2,  2.2,  3.2],
       [ 1.3,  2.3,  3.3]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM