リストがあり、それらにある要素を削除しようとしてい'pie'
ます。これは私がやったことです:
['applepie','orangepie', 'turkeycake']
for i in range(len(list)):
if "pie" in list[i]:
del list[i]
リストのインデックスを範囲外に取得し続けますがdel
、print
ステートメントに変更すると、要素が正常に出力されます。
反復処理中のリストからアイテムを削除する代わりに、Python の優れたリスト内包表記構文を使用して新しいリストを作成してみてください。
foods = ['applepie','orangepie', 'turkeycake']
pieless_foods = [f for f in foods if 'pie' not in f]
何かのようなもの:
stuff = ['applepie','orangepie', 'turkeycake']
stuff = [item for item in stuff if not item.endswith('pie')]
繰り返し処理しているオブジェクトを変更することは、ノーゴーと見なす必要があります。
反復中に要素を削除すると、サイズが変更され、IndexError が発生します。
コードを次のように書き換えることができます (リスト内包表記を使用)
L = [e for e in L if "pie" not in e]
エラーが発生する理由は、何かを削除するとリストの長さが変わるためです!
例:
first loop: i = 0, length of list will become 1 less because you delete "applepie" (length is now 2)
second loop: i = 1, length of list will now become just 1 because we delete "orangepie"
last/third loop: i = 2, Now you should see the problem, since i = 2 and the length of the list is only 1 (to clarify only list[0] have something in it!).
したがって、次のようなものを使用してください。
for item in in list:
if "pie" not in item:
new list.append(item)
別のより長い方法は、円グラフに遭遇したインデックスを書き留め、最初の for ループの後にそれらの要素を削除することです。