pythoncollections 모듈의 사용

컬렉션 모듈
collections 모듈:python 8대 유형 이외의 데이터 형식 제공
python 기본 8대 데이터 형식:
- 정형
- 부동 소수점
- 문자열
- 사전
- 목록
- 메타그룹
- 컬렉션
- 부울 유형
1. 구명 원조
구명 원조는 이름일 뿐이다
장면 적용:
① 좌표

#  : 
from collections import namedtuple

#  " " " " 
#  
point = namedtuple(" ", ["x", "y" ,"z"])  #  
# point = namedtuple(" ", "x y z")  #  , 
p = point(1, 2, 5)  #  namedtuple 

#  1 --> x , 2 --> y , 5 --> z
print(p)
print(p.x)
print(p.y)
print(p.z)
실행 결과:

 (x=1, y=2, z=5)
1
2
5
② 트럼프

#  
from collections import namedtuple

#  
card = namedtuple(" ", "color number")

#  
red_A = card(" ", "A")
print(red_A)
black_K = card(" ", "K")
print(black_K)
실행 결과:

 (color=' ', number='A')
 (color=' ', number='K')
③ 개인 정보

#  
from collections import namedtuple

p = namedtuple("china", "city name age")

ty = p("TB", "ty", "31")
print(ty)
실행 결과:

china(city='TB', name='ty', age='31')
2. 질서 있는 사전
python의 사전은 기본적으로 무질서합니다
collections에서 질서정연한 사전을 제공합니다:from collections import OrderedDict

# python 
dict1 = dict({"x": 1, "y": 2, "z": 3})
print(dict1, "  ------>   ")
print(dict1.get("x"))


#  collections 
from collections import OrderedDict

order_dict = OrderedDict({"x": 1, "y": 2, "z": 3})
print(order_dict, "  ------>   ")
print(order_dict.get("x"))  #  , .get() 
print(order_dict["x"])  #  , key 
print(order_dict.get("y"))
print(order_dict["y"])
print(order_dict.get("z"))
print(order_dict["z"])
실행 결과:

{'x': 1, 'y': 2, 'z': 3}  ------>   
1
OrderedDict([('x', 1), ('y', 2), ('z', 3)])  ------>   
1
1
2
2
3
3
이상은pythoncollections모듈의 사용에 대한 상세한 내용입니다.pythoncollections모듈에 대한 더 많은 자료는 저희 다른 관련 글을 주목해 주십시오!

좋은 웹페이지 즐겨찾기