简体   繁体   中英

Replacing elements in a list of lists, with elements from another list

I have two lists:

abc = [[1, 11, 111, 111], [2, 22, 222, 2222], [3, 33, 333, 3333]]
bbb = [12, 13, 34]

I want to replace the 2nd element from each sublist of list abc with element from bbb, so I can have a list that looks like this:

[[1, 12, 111, 111], [2, 13, 222, 2222], [3, 34, 333, 3333]]

I know I have to use list comprehension, but I just can't figure it out.

The best I can think of is:

newlist = [i[1]=bbb for i in abc]

You could do something like this, using zip :

abc = [[1, 11, 111, 111], [2, 22, 222, 2222], [3, 33, 333, 3333]]
bbb = [12, 13, 34]

result = [f[:1] + [s] + f[2:] for f, s in zip(abc, bbb)]

print(result)

Output

[[1, 12, 111, 111], [2, 13, 222, 2222], [3, 34, 333, 3333]]

You can use zip :

abc = [[1, 11, 111, 111], [2, 22, 222, 2222], [3, 33, 333, 3333]]
bbb = [12, 13, 34]
result = [[a, b, *c] for [a, _, *c], b in zip(abc, bbb)]

Output:

[[1, 12, 111, 111], [2, 13, 222, 2222], [3, 34, 333, 3333]]

This question has already been answered, but as an alternative, you could think about using numpy , especially if your arrays are large:

import numpy as np
abc = [[1, 11, 111, 111], [2, 22, 222, 2222], [3, 33, 333, 3333]]
bbb = [12, 13, 34]

abc = np.array(abc)
abc[:,1] = bbb

>>> abc
array([[   1,   12,  111,  111],
       [   2,   13,  222, 2222],
       [   3,   34,  333, 3333]])

# You can convert back to list too if so desired:
>>> abc.tolist()
[[1, 12, 111, 111], [2, 13, 222, 2222], [3, 34, 333, 3333]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM