在停止迭代中使用带有变量结果"next"语句



谁能解释一下为什么:

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

在下面做的其他事情给出了一个停止迭代

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

第一个有效是因为x总是大于 1000,因为x变量与您在上一行定义的x不同,而是来自 for x in tablex。所以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

最新更新