목록의 요소 쌍 반복
목록을 반복할 때 두 요소에 액세스해야 하는 상황이 자주 발생합니다. 시간. 이 문제를 해결하기 위해 쌍별 반복 개념을 활용할 수 있습니다.
이와 관련하여 Python에 내장된 zip() 기능이 도움이 될 수 있습니다. pairwise() 또는 grouped() 메서드는 반복 가능 항목을 사용하고 요소가 두 개인 연속적인 하위 시퀀스를 생성합니다. 이를 구현하는 방법은 다음과 같습니다.
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으로 설정하면 한 번에 세 가지 요소를 반복할 수 있습니다.
for x, y, z in grouped(l, 3): print("%d + %d + %d = %d" % (x, y, z, x + y + z))
이 접근 방식은 한 번만 나열하면 중간 목록이 필요하지 않습니다.
위 내용은 Python 목록에 있는 요소 쌍(또는 그룹)을 반복하려면 어떻게 해야 합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기