简体   繁体   English

在列表理解中创建列表

[英]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 [[char for line in grid] for i,char in enumerate(line) if len(line[i:])>3] #NameError:未定义名称'line'

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. 您应该在列表中移动第二个for循环和条件,而不是第一个。 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) . 当没有列表时,执行的顺序是-首先是循环- for line in grid ->第二是循环- 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. 上面的代码将保留该顺序,并为满足您条件的每一行创建一个字符作为单独的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM