将列表元素添加到列表列表的末尾

Mat*_*ttR 2 python

我有一个值列表,我想将其元素添加到列表列表中每个列表的末尾。有没有Pythonic或有效的方法来解决这个问题?

例如,给定:

x = [['a','b','c'],['d','e','f'],['g','h','i']]
y = [1,2,3]
Run Code Online (Sandbox Code Playgroud)

我期望: [['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]

我试过了:

list(zip(x,y))
Run Code Online (Sandbox Code Playgroud)

但是,这会产生:

[(['a', 'b', 'c'], 1), (['d', 'e', 'f'], 2), (['g', 'h', 'i'], 3)]
Run Code Online (Sandbox Code Playgroud)

我可以用这样的低效循环来解决它:

new_data = []
for i,x in enumerate(x):
    x.append(y[i])
    new_data.append(x)

print(new_data)
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
Run Code Online (Sandbox Code Playgroud)

Sam*_*ord 7

要建立一个新列表,我可能会这样做:

>>> x = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> y = [1,2,3]
>>> [a + [b] for a, b in zip(x, y)]
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
Run Code Online (Sandbox Code Playgroud)

如果你想x就地修改,则不需要使用enumerate,只需循环zip和appendy 元素到 x 元素:

>>> for a, b in zip(x, y):
...     a.append(b)
...
>>> x
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
Run Code Online (Sandbox Code Playgroud)