【问题标题】:What is this for loop inside parenthesis [duplicate]括号内的for循环是什么[重复]
【发布时间】:2020-10-03 22:05:15
【问题描述】:
my_list = [1,2,3,4,5,6,7,8,9,10]

gen_comp = (item for item in my_list if item > 3)

for item in gen_comp:
    print(item)

【问题讨论】:

标签: python generator-expression


【解决方案1】:

我添加了一些 cmets,希望对你有所帮助:

# create a list with 10 elements
my_list = [1,2,3,4,5,6,7,8,9,10]

# generate a list based on my_list and add only items if the value is over 3
# this is also known as tuple comprehension 
# that one creates a tuple containing every item in my_list that have a value greater then 3. 
gen_comp = (item for item in my_list if item > 3)

# print the new generated list gen_comp
for item in gen_comp:
    print(item)

输出:

4
5
6
7
8
9
10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2014-05-07
    相关资源
    最近更新 更多