简体   繁体   中英

Avoid the creation of sublist when using a list comprehension

If I have this list comprehension:

[list(range(0,x)) for x in [1, 2, 3]] 

I get

[[0], [0, 1], [0, 1, 2]]

But I would like to get:

[0, 0, 1, 0, 1, 2]

Noticed that the example above is just a minimal example.

I have read a lot of SO questions that explain how to flatten a list of lists but I have found nothing on how to avoid the creation of sublist inside the list comprehension.

Use a nested comprehension à la:

[y for x in [1,2,3] for y in range(x)]
# [0, 0, 1, 0, 1, 2]

Or, if you are into utils and cryptic brevity:

from itertools import chain

[*chain(*map(range, [1, 2, 3]))]
# or, as the traditionalists would suggest:
# list(chain.from_iterable(map(range, [1, 2, 3])))

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