给出了几个清单:
a = ["a1", "a2", "a3"]
b = ["b1", "b2", "b3"]
...
n = ["n1", "n2", "n3"]
以及新值列表:
new_vals = ["a4", "b4", "n4"]
我想得到:
["a1", "a2", "a3", "a4"]
["b1", "b2", "b3", "b4"]
...
["n1", "n2", "n3", "n4"]
当然,我可以使用循环和临时变量来完成此操作。似乎zip
,map
和list.extend
的组合应该更优雅地完成,但是我不知道。
答案 0 :(得分:5)
这样的事情:
a = ["a1", "a2", "a3"]
b = ["b1", "b2", "b3"]
# Put the list a, b ... in a big_list.
big_list = [a, b]
new_vals = ["a4", "b4", "n4"]
for i, new_val in enumerate(new_vals):
big_list[i].append(new_val)
答案 1 :(得分:2)
假设您有一个列表列表:
lsts = [ ['a1','a2','a3'],
['b1','b2','b3'],
['c1','c2','c3'] ]
以及一个列表,其中包含要追加到lsts
中每个列表末尾的新值:
lst = [ 'a4', 'b4', 'c4' ]
然后你可以使用列表理解:
new_lsts = [l + [x] for l, x in zip(lsts, lst)]
答案 2 :(得分:1)
面向map()的解决方案:
a = ["a1", "a2", "a3"]
b = ["b1", "b2", "b3"]
n = ["n1", "n2", "n3"]
new_vals = ["a4", "b4", "n4"]
map(lambda lst, x: lst.append(x), (a, b, n), new_vals)
并合并上面的列表建议列表:
lsts = [['a1','a2','a3'],
['b1','b2','b3'],
['c1','c2','c3']]
new_vals = ["a4", "b4", "c4"]
map(lambda lst, x: lst.append(x), lsts, new_vals)
这可能更好,因为它可以就地修改lsts而不是创建新的列表列表。