Manduss life

[Python] Tuple / Set / Dictionary / Counter 본문

전산/Python

[Python] Tuple / Set / Dictionary / Counter

만두쓰 2023. 1. 14. 16:38

Tuple

  • tuple 값 하나인 튜플은 반드시 ","를 붙여야함
    ex) t = (1,)

Set

  • set에서 여러개 추가시 update 사용
    ex) s.update([1, 2, 3])
    s.add(1) ## 1개 추가시 add 사용

  • 합집합 union |
    교집합 intersection &
    차집합 difference - 

Dictionary

  • for k, v in country_code.items() : ##for문에서 이렇게 많이 쓴다
    "korea" in country_code.keys() -> True
    82 in country_code.values() -> True

Queue

  • rotate -> n칸씩 오른쪽으로
    ex) deque([10, 0, 1, 2, 3, 4])
    deque_list.rotate(1)
    deque([4, 10, 0, 1, 2, 3])

  • extendleft -> 왼쪽으로 list 합치기
    deque([10, 0, 1, 2, 3, 4])
    deque_list.extend([5, 6])
    deque([5, 6, 10, 0, 1, 2, 3, 4])

DefaultDict

  • defaultdict -> 없는 key값을 부를 시 error를 출력하지 않고 default값 출력
    ex) 
    d = defualtdict(lambda : 0)
    d["first"] -> 0 ## not error

Counter

  • from collections import Counter
    ball_or_strike = ["B", "S", "S", "B", "B"]
    c = Counter(ball_or_strike)
    c -> Counter({'B':3, 'S':2})

  • ball_or_strike.elements
    ex)
    c = Counter({'B':3, 'S':4})
    list(c.elements()) -> ['B', 'B', 'B', 'S', 'S']

  • counter는 set 연산 가능 ex) +&|..

  • sorted(Counter(text).items(), key = lambda t : t[1], reverse = True)



새로 안 이론

  • list보다 deque가 더 빠르다. 10000번 loop에서 약 3배 이상 빠르네 

  • timeit 명령어 -> 여러번 돌려서 시간을 재준다. 오차까지 ! 알아두면 좋을 것
    ex) %timeit function()

  • namedtuple -> tuple형태의 class? 저장 가능

'전산 > Python' 카테고리의 다른 글

[Python] Class  (0) 2023.01.14
Comments