본문 바로가기
Programming/Python

파이썬에서 자료구조(data structure)를 간단하게 다루도록 도와주는 모듈

by Renechoi 2022. 10. 14.

부스트코스의 "머신러닝을 위한 파이썬" 강좌 필기 내용 

 

 

https://www.boostcourse.org/ai222/lecture/23091?isDesc=false 

 

 

 

# 자료구조에 대한 기본적인 모듈을 파이썬에서 제공해주는 라이브러리가 있음 
# collections라는 모듈 


### Collections 
'''
- List, Tuple, Dict에 대한 파이썬 built-in 확장 자료 구조 
- 편의성, 실행 효율 등으로 사용자에게 권장됨
- 아래의 모듈이 존재한다 
'''

# from collections import deque 
# from collections import Counter
# from collections import OrderedDict
# from collections import defaultdict
# from collections import namedtuple


## deque 
'''
- stack과 queue를 지원하는 모듈
- list에 비해 효율적인 자료 저장 방식을 지원함 
'''

from collections import deque
deque_list = deque()
for i in range(5):
    deque_list.append(i)
    # print(deque_list)
    # deque([0])
    # deque([0, 1])
    # deque([0, 1, 2])
    # deque([0, 1, 2, 3])
    # deque([0, 1, 2, 3, 4])
    
deque_list.appendleft(10)   # 생성된 리스트에서 앞에 10을 넣어준다 
# print(deque_list)
# deque([10, 0, 1, 2, 3, 4])    


deque_list.rotate(2)            # rotate로 인덱스를 돌려줌 
# print(deque_list)
# deque([3, 4, 10, 0, 1, 2])

deque_list.extend([5,6,7])
# print(deque_list)
# deque([3, 4, 10, 0, 1, 2, 5, 6, 7])

deque_list.extendleft([5,6,7])  # 왼쪼ㅓㄱ에 붙여주는 것도 가능 
# print(deque_list)
# deque([7, 6, 5, 3, 4, 10, 0, 1, 2, 5, 6, 7])

deque(reversed(deque_list))     # reverse 기능 
# deque([7, 6, 5, 2, 1, 0, 10, 4, 3, 5, 6, 7])




## OrderedDict 
'''
- dict와는 다르게 데이터를 입력한 순서대로 반환한다 
원래 dict는 저장한 순서로 출력하지 않음 
OrderedDict를 쓰면 순서대로 저장할 수 있음 '''

d={}
d['x']=100
d['y']=200
d['z']=300
d['l']=500

for k, v in d.items():
    None
    #print(k,v)




from collections import OrderedDict 
d= OrderedDict()
d['x']=100
d['y']=200
d['z']=300
d['l']=500


for k, v in d.items():
    None
    #print(k,v)


# sorting 할 때 orderdict로 선언해주고 sorting하면 편하게 가능 
for k, v in OrderedDict(sorted(d.items(), key=lambda t: t[1])).items():
    None
    #print(k,v )




## Defaultdict 
'''
- Dict 타입의 기본 값을 지정해줌 
d= dict()
print(d['first])
위와 같이 하면 아무것도 없는 상태이기 때문에 에러가 남 
'''

from collections import defaultdict

d=defaultdict(object)       # 딕셔너리 생성 
d=defaultdict(lambda:0)     # 디폴트 값을 0으로 설정해줌 
# print(d['first'])           # 키 값이 존재하지 않지만 초기값이 0이기 때문에 0으로 반환을 해줌      => 글자 카운트 할 때 defaultdict를 쓰면 없는 글자 처리할 때 편하게 할 수 있다 
# 0   



text = """A press release is the quickest and easiest way to get free publicity. If well written, a press release can result in multiple published articles about your firm and its products. And that can mean new prospects contacting you asking you to sell to them. Talk about low-hanging fruit!
What's more, press releases are cost effective. If the release results in an article that (for instance) appears to recommend your firm or your product, that article is more likely to drive prospects to contact you than a comparable paid advertisement.
However, most press releases never accomplish that. Most press releases are just spray and pray. Nobody reads them, least of all the reporters and editors for whom they're intended. Worst case, a badly-written press release simply makes your firm look clueless and stupid.
For example, a while back I received a press release containing the following sentence: "Release 6.0 doubles the level of functionality available, providing organizations of all sizes with a fast-to-deploy, highly robust, and easy-to-use solution to better acquire, retain, and serve customers."
Translation: "The new release does more stuff." Why the extra verbiage? As I explained in the post "Why Marketers Speak Biz Blab", the BS words are simply a way to try to make something unimportant seem important. And, let's face it, a 6.0 release of a product probably isn't all that important.
As a reporter, my immediate response to that press release was that it's not important because it expended an entire sentence saying absolutely nothing. And I assumed (probably rightly) that the company's marketing team was a bunch of idiots.""".lower().split()


word_count = {}                     # 워드 카운트로 기본 방식의 딕셔너리 => 글자세도록 => default를 쓰지 않으면 아래와 같이 써주어야 함 
for word in text:
    if word in word_count.keys():
        word_count[word] += 1       # 한개씩 가져와서 word_count에 넣어주어야 함        = 존재하면 1 그 다음부터 +1 씩 올려주어야 
    else:
        word_count[word] = 1        # 존재하지 않으면 1이라는 것으로 할 당을 해주어야 하는 것 
#print(word_count)



word_count = defaultdict(object)     # Default dictionary를 생성
word_count = defaultdict(lambda: 1)  # Default 값을 0으로 설정합
for word in text:
    word_count[word] += 1            # 이미 초기값이 있기 때문에 없는 것에 대해서 처리하지 않고 바로 1씩 올려줄 수 있음  
for i, v in OrderedDict(sorted(
        word_count.items(), key=lambda t: t[1], reverse=True)).items():             # 쉽게 정렬할 수 있다 
    None
    #print(i, v)




### Counter 
'''
- sequence 형 자료형에서 element의 개수를 세어줌 '''

from collections import Counter

c = Counter()
c =Counter('gallahand')
#print(c)
#Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'n': 1, 'd': 1})

c = Counter({'red':4, 'blue':2})
# print(list(c.elements()))                     # 반대로 풀어줄 수도 있다 
# ['red', 'red', 'red', 'red', 'blue', 'blue']




### Namedtuple 
'''
- tuple 형태로 데이터 구조체를 저장하는 방법
- 저장되는 data의 변수를 사전에 지정해서 저장함 
'''



from collections import namedtuple
Point = namedtuple('Point', ['x','y'])
p = Point(11, y=22)
# print(p[0]+p[1])
# 33


# x,y, = p
# print(x,y)
# print(p.x + p.y)
# print(Point(x=11, y=22))

 

 

 

 

반응형