Python에서 열거형 표현
Python 3.4 이상에서는 Enum 클래스를 사용하여 열거형을 기본적으로 정의할 수 있습니다. 이를 사용하려면 Python 3.4 이전 버전용 enum34 패키지를 설치하십시오.
from enum import Enum Animal = Enum('Animal', 'ant bee cat dog') print(Animal.ant) # Output: <animal.ant:> print(Animal['ant']) # Output: <animal.ant:> print(Animal.ant.name) # Output: 'ant'</animal.ant:></animal.ant:>
더 고급 enum 기술을 사용하려면 aenum 라이브러리 사용을 고려하십시오.
Python 3.4 이전 버전에 대한 대체 접근 방식
이전 Python 버전에서는 사용자 정의를 사용하여 열거형을 에뮬레이트할 수 있습니다. 함수:
def enum(**enums): return type('Enum', (), enums)
사용법:
Numbers = enum(ONE=1, TWO=2, THREE='three') print(Numbers.ONE) # Output: 1 print(Numbers.THREE) # Output: 'three'
다음을 사용하여 자동 열거를 지원할 수도 있습니다:
def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums)
사용법:
Numbers = enum('ZERO', 'ONE', 'TWO') print(Numbers.ZERO) # Output: 0 print(Numbers.TWO) # Output: 2
또는 Python 3.8에서 Typing.Literal을 사용하거나 열거형을 정의하기 위한 이전 버전의 Typing_extensions.Literal:
from typing import Literal # Python >= 3.8 from typing_extensions import Literal # Python 2.7, 3.4-3.7 Animal = Literal['ant', 'bee', 'cat', 'dog'] def hello_animal(animal: Animal): print(f"hello {animal}")
위 내용은 Python에서 열거형을 효과적으로 표현하려면 어떻게 해야 합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

contiguousUousUousUlorAllocationScrucialForraysbecauseItAllowsOfficationAndFastElementAccess.1) ItenableSconstantTimeAccess, o (1), DuetodirectAddressCalculation.2) Itimprovesceeffiency theMultipleementFetchespercacheline.3) Itsimplififiesmomorym

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

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

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

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