简体   繁体   中英

Create a list within a list comprehension

How can I make this:

[char for line in grid for i,char in enumerate(line) if len(line[i:])>3]

return a list of char's for each line that meet the criteria:

[[char for line in grid] for i,char in enumerate(line) if len(line[i:])>3] #NameError: name 'line' is not defined

I am guessing you are looking for -

[[char for i,char in enumerate(line) if len(line[i:])>3] for line in grid]

You should move the second for loop and condition inside the list, not the first one. When there were no lists, the order of execution was - first for loop - for line in grid -> second for loop - for i,char in enumerate(line) .

The above would preserve that order, and create chars for each line meeting your condition as a separate list.

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