Python でリストの値を条件付きで置換する
リストを操作する場合、多くの場合、特定の条件に基づいて値を変更する必要があります。一般的なタスクの 1 つは、条件が True と評価された場合に値を None に置き換えることです。
リスト内包表記を使用した解決策
これを行う最も効率的な方法は、リスト内包表記を使用することです。 .
<code class="python">new_items = [x if x % 2 else None for x in items]</code>
ここで、 items は元のリストであり、 x % 2 は item が偶数であるかどうかをチェックします。 true の場合、項目は None に置き換えられます。それ以外の場合は、元の値が保持されます。
インプレース変更
元のリストをインプレースで変更することは可能ですが、効率上の理由からお勧めできません。
<code class="python">for index, item in enumerate(items): if not (item % 2): items[index] = None</code>
このアプローチではリスト全体を 2 回繰り返す必要があり、リストが大きい場合はコストがかかる可能性があります。
タイミングの比較
2 つのアプローチのベンチマーク特に大きなリストの場合、リストの理解が大幅に高速化されていることを示しています。
Python 3.6.3:
(In-place) 1.06 µs ± 33.7 ns per loop (List comprehension) 891 ns ± 13.6 ns per loop
Python 2.7.6:
(In-place) 1.27 µs per loop (List comprehension) 1.14 µs per loop
以上がPython でリストの値を条件付きで置き換える方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

pythonusesahybridmodelofcompilation andtertation:1)thepythoninterpretercompilessourcodeodeplatform-indopent bytecode.2)thepythonvirtualmachine(pvm)thenexecuteTesthisbytecode、balancingeaseoputhswithporformance。

pythonisbothintersedand compiled.1)it'scompiledtobytecode forportabalityacrossplatforms.2)bytecodeisthenは解釈され、開発を許可します。

loopsareideal whenyouwhenyouknumberofiterationsinadvance、foreleloopsarebetterforsituationsは、loopsaremoreedilaConditionismetを使用します

henthenumber ofiterationsisknown advanceの場合、dopendonacondition.1)forloopsareideal foriterating over for -for -for -saredaverseversives likelistorarrays.2)whileopsaresupasiable forsaresutable forscenarioswheretheloopcontinupcontinuspificcond

pythonisnotpurelyLepted; itusesahybridapproachofbytecodecodecodecodecodecodedruntimerttation.1)pythoncompilessourcodeintobytecode、whodythepythonvirtualmachine(pvm).2)

ToconcatenateListsinpythothesheElements、使用:1)Operatortokeepduplicates、2)asettoremoveduplicates、or3)listcomplunting for controloverduplicates、各メトドハスディフェルフェルフェントパフォーマンスアンドソーダーインプリテーション。

pythonisantertedlanguage、useaseofuseandflexibility-butfactingporformantationationsincriticalapplications.1)解釈されたlikepythonexecuteline-by-lineを解釈します

Useforloopswhenthenumberofiterationsisknowninadvance、andwhiloopswheniterationsdependonacondition.1)forloopsareidealforsecenceslikelistoranges.2)


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。
