Extending several lists elegantly
Given several lists:
a = ["a1", "a2", "a3"]
b = ["b1", "b2", "b3"]
...
n = ["n1", "n2", "n3"]
And a list of new values:
new_vals = ["开发者_开发问答a4", "b4", "n4"]
I would like to get:
["a1", "a2", "a3", "a4"]
["b1", "b2", "b3", "b4"]
...
["n1", "n2", "n3", "n4"]
I can do this with loops and temporary variables, of course. It seems like come combination of zip
, map
, and list.extend
should do it more elegantly, but is eluding me.
Something like this:
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)
Suppose you have a list of lists:
lsts = [ ['a1','a2','a3'],
['b1','b2','b3'],
['c1','c2','c3'] ]
and a list that you of new values that you want to append to the end of each list in lsts
:
lst = [ 'a4', 'b4', 'c4' ]
Then you can use a list comprehension:
new_lsts = [l + [x] for l, x in zip(lsts, lst)]
A map() oriented solution:
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)
And incorporating the list of lists suggestions above:
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)
This might be preferable since it modifies lsts in-place instead of creating a new list of lists.
精彩评论