简体   繁体   中英

Append list elements to list of lists in python

Given the following lists:

list1 = [[1, 2],
         [3, 4],
         [5, 6],
         [7, 8]]
list2 = [10, 11, 12, 13]

What is the best way to change list1 so it becomes the following list in python?

[[1, 2, 10],
 [3, 4, 11],
 [5, 6, 12],
 [7, 8, 13]]

You can use zip :

[x + [y] for x, y in zip(list1, list2)]
# [[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]

To modify list1 in place, you could do:

for x, y in zip(list1, list2):
    x.append(y)

list1
# [[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]

Or, a comprehension with unpacking, after zip ing, if you're using Python >= 3.5:

>>> l = [[*i, j] for i,j in zip(list1, list2)]
>>> print(l)
[[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]

Of course, if the list sizes might differ, you'd be better off using zip_longest from itertools to gracefully handle the extra elements.

You can make it this way:

for i in range(len(list1)):
    list1[i] += [list2[i]]

print(list1)

Output

[[1, 2, 10], [3, 4, 11], [5, 6, 12], [7, 8, 13]]

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