リストから項目を削除するときの間違ったループ
リストを反復処理してループ内の項目を削除すると、予期しない動作が発生する可能性があります。次のコードを考えてみましょう:
<code class="python">letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'] for i in letters: letters.remove(i) print(letters)</code>
このコードでは、期待どおりにすべての項目を削除する代わりに、次の出力が生成されます:
['b', 'd', 'f', 'h', 'j', 'l']
この一見奇妙な動作は、Python のドキュメントで説明されています。
[I] ループ内で反復されるシーケンスを変更するのは安全ではありません。反復処理中のリストを変更する必要がある場合は、コピーを反復処理する必要があります。
この特定のケースでは、項目を削除した後に反復変数 i が更新され、その結果、次の項目のインデックスが更新されます。スキップされるループ。
項目を正確に削除するための再書き込み
この動作を修正するには、リストのコピーを反復処理するか、別の方法を使用して項目を削除する必要があります。 。以下に 3 つのオプションがあります:
- リスト全体を削除します:
<code class="python">del letters[:]</code>
- リストを空のリストに置き換えます:
<code class="python">letters[:] = []</code>
- 新しいリストを作成します:
<code class="python">letters = []</code>
または、特定のリストを削除する必要がある場合は、条件に基づいて項目を削除するには、内包表記または filter() 関数を使用してリストをフィルタリングできます。
<code class="python">letters = [letter for letter in letters if letter not in ['a', 'c', 'e', 'g', 'i', 'k']]</code>
<code class="python">letters = list(filter(lambda letter: letter not in ['a', 'c', 'e', 'g', 'i', 'k'], letters))</code>
これらのガイドラインに従うことで、Python でリストから項目を正確かつ効率的に削除できます。 .
以上がループを使用してリストから項目を削除するときの予期しない動作に対処する方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

forhandlinglaredataSetsinpython、usenumpyArrays forbetterperformance.1)numpyarraysarememory-effictientandfasterfornumericaloperations.2)nusinnnnedarytypeconversions.3)レバレッジベクトル化は、測定済みのマネージメーシェイメージーウェイズデイタイです

inpython、listsusedynamicmemoryallocation with allocation、whilenumpyArraysalocatefixedmemory.1)listsallocatemorememorythanneededededinitivative.2)numpyArrayasallocateexactmemoryforements、rededicablebutlessflexibilityを提供します。

inpython、youcanspecthedatatypeyfelemeremodelernspant.1)usenpynernrump.1)usenpynerp.dloatp.ploatm64、フォーマーpreciscontrolatatypes。

numpyisessentialfornumericalcomputinginpythonduetoitsspeed、memory efficiency、andcomprehensivematicalfunctions.1)それは、performsoperations.2)numpyArraysaremoremory-efficientthanpythonlists.3)Itofderangeofmathematicaloperty

contiguousMemoryAllocationisucial forArraysは、ForeffienceAndfastelementAccess.1)iteenablesConstantTimeAccess、O(1)、DuetodirectAddresscalculation.2)itemprovesefficiencyByAllowingMultiblementFechesperCacheLine.3)itimplifieMememm

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

SublimeText3 中国語版
中国語版、とても使いやすい

Safe Exam Browser
Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

ホットトピック









