在StopIteration中使用带有变量result的“next”语句

2024-04-26 11:50:42 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释为什么:

table ={1249.99: 36.30, 
        1749.99: 54.50, 
        2249.99: 72.70, 
        2749.99: 90.80, 
        3249.99: 109.00, 
        3749.99: 127.20,
        4249.99: 145.30}

x = 1000
y = next(x for x in table if x > 1000) work fines

另一方面,执行下面的操作会给出一个StopIteration

y = next(x for x in table if x > x)

Tags: inforiftablenextworkstopiterationfines
1条回答
网友
1楼 · 发布于 2024-04-26 11:50:42

第一个是有效的,因为x总是大于1000,因为x变量与前一行定义的x不同,而是for x in table中的x。所以xtable的下一个键。所有的键都大于1000,所以创建的迭代器不是空的。你知道吗

next(x for x in table if x > 1000)
# similar to:
# next(iter((1249.99, 1749.99, 249.99, 2749.99, 3249.99, 3749.99, 4249.99)))

第二个例子提出了StopIteration,因为x永远不会大于x,这意味着您将从一个空迭代器获得下一个迭代。你知道吗

next(x for x in table if x > x)
# similar to:
# next(iter(()))

考虑以下几点:

您的代码等效于:

def gen_a(table):
    for x in table: # same as for x in table.keys()
        if x > 1000:
            yield x

def gen_b(table):
    for x in table:  # same as for x in table.keys()
        if x > x: # will never happen
            yield x

table ={1249.99: 36.30, 
        1749.99: 54.50, 
        2249.99: 72.70, 
        2749.99: 90.80, 
        3249.99: 109.00, 
        3749.99: 127.20,
        4249.99: 145.30}

x = 1000 # note that x isn't in the same scope as the other x's

print(next(gen_a(table))) # result varies since dict are unordered, I got 4249.99

print(next(gen_b(table))) # raises a StopIteration

相关问题 更多 >