リスト内の要素のペアの反復
リストを反復するとき、次の 2 つの要素にアクセスする必要がある状況によく遭遇します。ある時間。これに対処するには、ペアワイズ反復の概念を利用できます。
Python の組み込み zip() 関数は、この点で役立ちます。 pairwise() メソッドまたは grouped() メソッドは反復可能オブジェクトを消費し、連続する 2 要素のサブシーケンスを生成します。実装方法は次のとおりです:
def pairwise(iterable): "s -> (s0, s1), (s2, s3), (s4, s5), ..." a = iter(iterable) return zip(a, a)
この関数を使用して、リスト [1, 2, 3, 4, 5, 6] を考えてみましょう。ペアごとの反復を示す:
for x, y in pairwise(l): print("%d + %d = %d" % (x, y, x + y))
これにより、次の出力が生成されます:
1 + 2 = 3 3 + 4 = 7 5 + 6 = 11
あるいは、grouped() 関数を使用すると、一度に n 個の要素を反復できます。実装は次のとおりです。
def grouped(iterable, n=2): "s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..." return zip(*[iter(iterable)] * n)
たとえば、n を 3 に設定すると、一度に 3 つの要素を反復できます。
for x, y, z in grouped(l, 3): print("%d + %d + %d = %d" % (x, y, z, x + y + z))
このアプローチは、リストを一度だけ作成し、中間リストの必要性を排除します。
以上が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 英語版
推奨: Win バージョン、コードプロンプトをサポート!

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

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

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

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター
