2016-10-18 14 views
0

私は機能を使用してリストcomprehentionのpop要素にしようとしてきました。私の端末セッションは、次のようになります。不完全なリストがリスト内のポップアップ

enter image description here

をしかし、私は、問題が発生しなかった文字列と同じことをしようとしたとき:

enter image description here

誰かがで起こっている私に説明できます最初のシナリオ?なぜg.pop(0)が返されたのは[1, 2]ですか?

コピーのためのトランスクリプト(なぜスタックは、折りたたみ可能なセクションを持っていません):

>>> from itertools import takewhile 
from itertools import takewhile 
>>> g = [1,2,3,4,5] 
>>> [a for a in takewhile(lambda x: x < 4, g)] 
[1, 2, 3] 
>>> [g.pop() for _ in takewhile(lambda x: x < 4, g)] 
[5, 4, 3] 
>>> g = [1,2,3,4,5] 
>>> [g.pop(0) for _ in takewhile(lambda x: x < 4, g)] 
[1, 2] 

>>> g = ['1', '2', '3', '4', '5'] 
>>> [a for a in takewhile(lambda x: x != '4', g)] 
['1', '2', '3'] 
>>> [g.pop() for _ in takewhile(lambda x: x != '4', g)] 
['5', '4', '3'] 
>>> g = ['1', '2', '3', '4', '5'] 
>>> [g.pop(0) for _ in takewhile(lambda x: x != '4', g)] 
['1', '2', '3'] 

答えて

1

私はRuntimeError: deque mutated during iterationを上げdequeを使用しようとしたので、私は、それを考え出しました。

実行は次のようなものです。それは第二の場合で働いていた理由を反復'4'中にヒットされていないため、

  1. g[0] = 1 < 4; g.pop(0) => 1
  2. g[1] = 3 < 4; g.pop(0) => 2
  3. g[2] = 5 > 4; break

これも、説明しています。

関連する問題