在 StopIteration 中使用带有变量结果的 "next" 语句

using "next" statement with variable result in StopIteration

谁能解释一下原因:

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)

第一个有效,因为 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