简体   繁体   中英

Appending an element to a list of arrays (in the most concise idiomatic way)

I wrote this code:

alist = [[0], [1], [2]]
blist = [-1, 0, 1]

for a, b in zip(alist, blist):
    a.append(b)

output is [[0, -1], [1, 0], [2, 1]]

It works, but is there a way to remove the loop entirely?

Your code is fine IMHO. It's readable, concise and makes it clear that you want to modify alist in place.

If you want to avoid any explicit loop, you could work with numpy arrays and use np.stack :

import numpy as np
a = np.array([[0, 1], [1, 2], [2, 3]])
b = np.array([2, 3, 4])
np.column_stack([a, b])

It outputs:

array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])
>>> alist = [[0], [1], [2]]
>>> blist = [-1, 0, 1]
>>> [a + [b] for a, b in zip(alist, blist)]
[[0, -1], [1, 0], [2, 1]]

will do what you want (without modifying alist), though it's not pretty

If you don't mind to have a list of tuples as a result, I find this solution very readable.

>>> alist = [[0], [1], [2]]
>>> blist = [-1, 0, 1] 
>>> import itertools as it
>>> list(zip(it.chain(*alist), blist))
[(0, -1), (1, 0), (2, 1)]

If you must have a list of lists:

list(list(el) for el in zip(it.chain(*alist), blist))

Basically, I am unpacking the variable alist into positional arguments, which I then pass to itertools.chain() . This results in a flat list [0, 1, 2] . After that, you can simple zip the two lists and get the desired result without using a for loop. It is not the fastest but a valid, possible solution.

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