파이썬에서 알아두면 좋을 자료형

류재환·2022년 9월 20일
0

#1 Counter

  • Counter은 Sequence type의 원소들의 개수를 dict 형태로 반환해준다.
from collections import Counter
c=Counter('harry potter')
print(c)

출력 : Counter({'r': 3, 't': 2, 'h': 1, 'a': 1, 'y': 1, ' ': 1, 'p': 1, 'o': 1, 'e': 1})

  • 파라메터로는 dict타입도 keyword 타입도 사용 가능하다.
c=Counter({'a':2,'b':3})
print(c)
c=Counter(c=4,d=5)
print(c)

출력 : Counter({'b': 3, 'a': 2})
Counter({'d': 5, 'c': 4})

  • 다양한 연산자를 지원한다.
c=Counter({'a':2,'b':3,'c':5,'d':6})
d=Counter(a=1,b=2,c=4,d=5,e=5)
print(c+d)
print(c-d)
print(c&d)
print(c|d)

출력 : Counter({'d': 11, 'c': 9, 'b': 5, 'e': 5, 'a': 3})
Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1})
Counter({'d': 5, 'c': 4, 'b': 2, 'a': 1})
Counter({'d': 6, 'c': 5, 'e': 5, 'b': 3, 'a': 2})

#2 namedtuple

  • tuple형태로 저장하지만 사전에 변수명을 지정해서 사용한다.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y', 'z'])
p = Point(10, z=30, y=20)
print(p[0] + p[1],end=" ")
print(p[0] + p[2],end=" ")
print(p.x + p.y + p.z)

출력 : 30 40 60

  • 선언은 list, 콤마 구분, 띄어쓰기 구분으로 할 수 있다.
student = namedtuple('student','age height')
game = namedtuple('game','cost,volume')
s=student(20, 170)
g=game(volume=3,cost=10)
profile
비전공자의 개발자 도전기

0개의 댓글