파이썬 마스터 하기 8. collections 모듈

2023. 1. 16. 15:00·Python/개념 및 정리
반응형

collections에는 List, Tuple, Dictionary에 대한 모듈을 제공하며 이 모듈들은 매우 편리합니다!!

알아두시면 좋을것 같아서 파이썬 마스터 하기에서 다뤘습니다.

 

1. deque

2. counter

3. orderedDict

4. namedTuple

 

1. deque

deque는 제가 백준 문제와 함께 설명한 글이 있어서 글로 대체하겠습니다.

https://solution-is-here.tistory.com/117

 

백준(G5) 5430번: AC (파이썬, Python3) 및 deque 설명

https://www.acmicpc.net/problem/5430 5430번: AC 각 테스트 케이스에 대해서, 입력으로 주어진 정수 배열에 함수를 수행한 결과를 출력한다. 만약, 에러가 발생한 경우에는 error를 출력한다. www.acmicpc.net 파

solution-is-here.tistory.com

 

2. counter

1
from collections import Counter
cs

collections 모듈은 별도의 설치 없이 파이썬만 설치되어 있으면 자동적으로 되기 때문에 다른 모듈들 보다 편리하다.

counter 모듈은 문자 / 단어의 개수를 세기, 사전처럼 사용하기, set의 연산 지원하기등의 기능이 있습니다.

 

1. 문자 / 단어의 개수 세기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from collections import Counter
 
text = """It has been suggested that “organic” methods, defined as those in which only natural products can be used as inputs, 
would be less damaging to the biosphere. Large-scale adoption of “organic” farming methods, 
however, would  reduce yields and increase production costs for many major crops. Inorganic nitrogen supplies are  
essential for maintaining moderate to high levels of productivity for many of the non-leguminous crop species, 
because organic supplies of nitrogenous materials often are either limited or more expensive than inorganic nitrogen fertilizers.
 In addition, there are  benefits to the extensive use of either manure or legumes as “green manure” crops.
  In many cases, weed control can be very difficult or require much hand labor if chemicals cannot be used, 
  and  fewer people are willing to do this work as societies become wealthier. Some methods used in “organic” farming, 
  however, such as the sensible use of crop rotations and specific combinations of cropping and livestock enterprises, 
can make important  contributions to the sustainability of rural ecosystems.""".lower().split()
 
print(Counter(text))
print(Counter(text)["as"])
Colored by Color Scripter
cs

수능영어 30번 지문을 빌려서 설명하겠다!

"""을 사용해서 문자열을 받은 뒤 lower 함수와 split 함수를 이용해서 문자열에서 단어를 소문자로 바꾸고 분리했다.

단어로 분리했기때문에 counter 함수는 문자가 아닌 단어의 개수를 계산하게 된다.

답을 보니 내가 고등학교때 정말 많은 영어 단어를 외웠구나 라는 생각이 든다....

어쨌든 counter 함수를 사용해서 각 단어들의 빈도수를 계산하고 counter(text)["as"]을 이용해서 as가 5번 나온다는 것을 알 수 있었다.

 

2. 사전처럼 사용하기

1
2
Counter = Counter("hello")
print(Counter)
cs

평범한 함수처럼 보이지만 결과값을 보면 딕셔너리와 값 출력 형태가 비슷함을 알 수 있습니다.

1
2
Counter["l"] += 1
Counter["h"] -= 1
cs

이렇게 값을 더하고 뺄 수도 있다.

 

3. set 연산 지원하기

1
2
3
4
5
6
c = Counter("hello")
d = Counter("almalibre")
 
print(c + d)
print(c & d)
print(c | d)
cs

c와 d에 있는 원소를 합치거나 다양한 집합 연산을 사용할 수 있다.

 

3. orderDict

Dict type의 값을 value 또는 key 값으로 정렬할 때 사용 가능하다.

순서 있는 dictionary라고 생각하면 쉽다.

1
2
for k, v in OrderedDict(sorted(d.items(), key=lambda t: t[0])).items():
    print(k, v)
Colored by Color Scripter
cs

t[0]은 알파벳이기 때문에 key값으로 정렬했다고 생각하면 쉽다.

 

1
2
for k, v in OrderedDict(sorted(d.items(), key=lambda t: t[1])).items():
    print(k, v)
Colored by Color Scripter
cs

t[1]은 숫자여서 value 값으로 정렬한 것이다.

 

4. namedTuple

data를 Tuple형태로 저장하는 방법이다.

1
2
3
4
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
print(p[0] + p[1])
cs

['x','y']라는 틀을 만든 뒤, 11과 22라는 값을 튜플 형식으로 넣어주었다.

결과 값은 33이 나온다.

1
2
3
Point = namedtuple('Point', ['x', 'y'])
Point = namedtuple('point','x y')
Point = namedtuple('point','x,y')
cs

정의하는 방법은 리스트 형식, 띄어쓰기로 구분하기, 쉼표로 구분하기 등이 있습니다.

반응형
'Python/개념 및 정리' 카테고리의 다른 글
  • 리스트 컴프리헨션을 사용해야 하는 이유 [Python]
  • 알아두면 좋은 에라토스테네스의 체(파이썬,Python3) & 백준(S2) 4948번: 베르트랑 공준
  • 알면 좋은 파이썬 스타일 코드들
  • 파이썬 마스터 하기 7. 넘파이(numpy)
코딩하는_대학생
코딩하는_대학생
Java Developer, Open Source Enthusiast, Proud Son
  • 코딩하는_대학생
    코딩하는 대학생에서 개발자까지
    코딩하는_대학생
  • 전체
    오늘
    어제
    • 분류 전체보기 (218)
      • 코딩하는 대학생의 책 추천 (8)
        • 클린코드 (5)
        • 헤드퍼스트 디자인패턴 (3)
      • Backend (8)
        • Spring (14)
        • AWS (3)
        • 회고 (4)
        • Redis (5)
        • 다양한 시각에서 바라본 백엔드 (3)
      • Python (35)
        • 개념 및 정리 (15)
        • 백준 문제풀이 (20)
      • JAVA (17)
        • 개념 및 정리 (14)
        • 백준 문제풀이 (2)
      • 왜? (7)
      • C언어 (42)
        • 개념 및 정리 (9)
        • 백준 문제풀이 (32)
      • 개인 공부 (27)
        • 대학 수학 (5)
        • 대학 영어 (10)
        • 시계열데이터 처리 및 분석 (5)
        • 컴퓨터 네트워크 (6)
        • 운영체제 (1)
      • 솔직 리뷰 (23)
        • 꿀팁 (6)
        • IT기기 (1)
        • 국내 여행 (7)
        • 맛집 (2)
        • 알바 리뷰 (2)
      • 대외활동 (17)
        • 체리피우미 3기 (4)
        • 꿀잠이들 6기 (13)
      • 음식 평가 (1)
      • 일상 & 근황 (2)
  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
코딩하는_대학생
파이썬 마스터 하기 8. collections 모듈
상단으로

티스토리툴바