2017-05-16 8 views
1

内の変数結果と「次」の文を使用した:以下のことをやって一方誰も理由を説明することができます呼び出すと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 

xは常になりますので、最初のものは作品を呼び出すとStopIterationに

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

複製することはできません両方 'あなた' table'は、それが実証するために何かを持っているべきStopIteration' – AChampion

+0

を上げます問題? – mgilson

+0

'x> x'は決して真ではないので、イテレータは*常に*空です –

答えて

0

を与えますx変数が前の行で定義したxと同じではなく、であるため、xからfor x in table。だからxtableの次のキーです。そして、すべてのキーが1000より大きいので、作成されたイテレータは空ではありません。 xあなたは空のイテレータから次の反復を取得していることを意味する、xより大きくなることはありませんので、

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を上げました。

あなたのコードはこれと同等です:

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 
+1

ありがとう、それは非常に詳細で理解しやすい回答でした。非常に教育的。 – raymund

関連する問題