Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 优雅地扩展多个列表_Python_List - Fatal编程技术网

Python 优雅地扩展多个列表

Python 优雅地扩展多个列表,python,list,Python,List,给出了几个列表: 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组合而成

给出了几个列表:

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
应该做得更优雅,但我却无法做到这一点。

类似这样的事情:

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)

假设您有一个列表列表:

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)]
面向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)

这可能更可取,因为它会就地修改LST,而不是创建新的列表。

这是否意味着您有14个列表和3个新值?您如何匹配新值和原始列表?值是否总是以列表的变量名开始?更为python:第1行:
对于big_子列表,zip中的new_val(big_list,new_val):
和第2行:
big_子列表。append(new_val)
确实不错,+1。一开始可能令人惊讶的是,只需忽略映射的结果,因为append返回None。