A には、None の項目が含まれる可能性のあるリストがあります。これらの項目を削除したいのですが、リストの最後にある場合にのみ削除したいので、次のようになります。
[None, "Hello", None, "World", None, None]
# Would become:
[None, "Hello", None, "World"]
関数を書いたのですが、これが Python で実行する正しい方法かどうかわかりません。
def shrink(lst):
# Start from the end of the list.
i = len(lst) -1
while i >= 0:
if lst[i] is None:
# Remove the item if it is None.
lst.pop(i)
else:
# We want to preserve 'None' items in the middle of the list, so stop as soon as we hit something not None.
break
# Move through the list backwards.
i -= 1
代替としてリストの内包表記もありますが、これは非効率的で読みにくくなるようです。
myList = [x for index, x in enumerate(myList) if x is not None or myList[index +1:] != [None] * (len(myList[index +1:]))]
リストの最後から「None」の項目を削除する Python の方法は何ですか?
ベストアンサー1
リストの最後から破棄するのが効率的です。
while lst[-1] is None:
del lst[-1]
必要に応じて安全策を追加しますIndexError: pop from empty list
。空のリストで処理を続行することを正常と見なすべきか、エラー状態と見なすべきかは、特定のアプリケーションによって異なります。
while lst and lst[-1] is None:
del lst[-1]