1

I need to create a new list merging two lists where one of them is a list of lists. Here's what I need to do:

a = [[2, 1, 4, 5, 0], [3, 6, 5, 4, 8], [2, 1, 4, 7, 8], [3, 4, 9, 5, 6], [7, 5, 2, 1, 1]]
b = [2, 3, 5, 0, 8]
c = []

for indx, item in enumerate(a):
    c.append([item, b[indx]])

This generates c as:

[[[2, 1, 4, 5, 0], 2], [[3, 6, 5, 4, 8], 3], [[2, 1, 4, 7, 8], 5], [[3, 4, 9, 5, 6], 0], [[7, 5, 2, 1, 1], 8]]

but I would need it to look like:

[[2, 1, 4, 5, 0, 2], [3, 6, 5, 4, 8, 3], [2, 1, 4, 7, 8, 5], [3, 4, 9, 5, 6, 0], [7, 5, 2, 1, 1], 8]

I've tried adding a * in front of item to unpack the elements but that doesn't work.

4

2 回答 2

2

只需连接项目以创建一个列表,item其中的元素来自b

for indx, item in enumerate(a):
    c.append(item + [b[indx]])

您可以使用以下zip()函数简化循环:

for a_item, b_item in zip(a, b):
    c.append(a_item + [b_item])

然后将整个定义c移至列表推导:

c = [a_item + [b_item] for a_item, b_item in zip(a, b)]

演示:

>>> a = [[2, 1, 4, 5, 0], [3, 6, 5, 4, 8], [2, 1, 4, 7, 8], [3, 4, 9, 5, 6], [7, 5, 2, 1, 1]]
>>> b = [2, 3, 5, 0, 8]
>>> [a_item + [b_item] for a_item, b_item in zip(a, b)]
[[2, 1, 4, 5, 0, 2], [3, 6, 5, 4, 8, 3], [2, 1, 4, 7, 8, 5], [3, 4, 9, 5, 6, 0], [7, 5, 2, 1, 1, 8]]
于 2013-07-22T18:36:15.620 回答
2

您可以使用zip()函数和列表理解

>>> a = [[2, 1, 4, 5, 0], [3, 6, 5, 4, 8], [2, 1, 4, 7, 8], [3, 4, 9, 5, 6], [7, 5, 2, 1, 1]]
>>> b = [2, 3, 5, 0, 8]
>>> [elem1 + [elem2] for elem1, elem2 in zip(a, b)]
[[2, 1, 4, 5, 0, 2], [3, 6, 5, 4, 8, 3], [2, 1, 4, 7, 8, 5], [3, 4, 9, 5, 6, 0], [7, 5, 2, 1, 1, 8]]
于 2013-07-22T18:38:42.170 回答