Python에서 조건부로 목록 값 바꾸기
목록으로 작업할 때 특정 조건에 따라 값을 수정해야 하는 경우가 많습니다. 일반적인 작업 중 하나는 조건이 True로 평가되는 경우 값을 None으로 바꾸는 것입니다.
List Comprehension을 사용한 솔루션
이를 수행하는 가장 효율적인 방법은 List Comprehension을 사용하는 것입니다. .
<code class="python">new_items = [x if x % 2 else None for x in items]</code>
여기서 items는 원래 목록이고 x % 2는 항목이 짝수인지 확인합니다. true인 경우 항목을 없음으로 대체합니다. 그렇지 않으면 원래 값을 유지합니다.
내부 수정
원본 목록을 내부에서 수정하는 것은 가능하지만 효율성상의 이유로 권장되지 않습니다.
<code class="python">for index, item in enumerate(items): if not (item % 2): items[index] = None</code>
이 접근 방식을 사용하려면 전체 목록을 두 번 반복해야 하며, 큰 목록의 경우 비용이 많이 들 수 있습니다.
타이밍 비교
두 접근 방식 벤치마킹 특히 큰 목록의 경우 목록 이해가 훨씬 더 빠르다는 것을 보여줍니다.
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

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

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

WebStorm Mac 버전
유용한 JavaScript 개발 도구

Dreamweaver Mac版
시각적 웹 개발 도구