简体   繁体   中英

Two values in list comprehension

I attempted this list comprehension:

[sqrt(x), x**2 for x in range(rng)]

but apparently this syntax doesn't work. I suppose I could do something like this:

[fn(x), fn(x) for x in range(rng) for fn in (sqrt(), lambda x: x**2)]

but is there no cleaner way?

Edit: let's say rng is 3. I'd want an output of [0, 0, 1, 1, √2, 4]

You have a few options:

[fx for x in range(rng) for fx in [sqrt(x), x**2]]

or:

list(itertools.chain.from_iterable([sqrt(x), x**2] for x in range(rng)))

You can use double for-loop:

from math import sqrt
rng = 3
print([item for x in range(rng) for item in (sqrt(x), x**2)])
# [0.0, 0, 1.0, 1, 1.4142135623730951, 4]

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