Let's assume we have 3 arrays, index, a and b. How can I create arrays c and d just passing through index once?
c = [a[i] for i in index]
d = [b[i] for i in index]
Is there a way to create these arrays with a sigle generator?
You can use the zip
function:
c, d = zip(*((a[i], b[i]) for i in index))
If you want c
and d
to be lists you can use map
:
c, d = map(list, zip(*((a[i], b[i]) for i in index)))
If you want something longer (but maybe clearer), you could build a generator:
def g(a, b, index):
for i in index:
yield a[i], b[i]
c, d = zip(*g(a, b, index))
I will use zip with tuple expansion using *
c,d = zip(*((a[i],b[i]) for i in index))
Here it expands a[i] and b[i] in pairs using zip from generator expression.
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.