본문 바로가기

Engineering WIKI/Python51

any, all 함수 any([False, False, False]) # False any([False, True, False]) #True any 함수는 Iteration 이 가능한 객체를 받아 (위의 예에서는 list) 그 항목을 돌면서 어느 하나라도 True 이면 결과로 True를 리턴 한다는 것을 알 수 있었습니다. all([False, True, False]) # False all([True, True, True]) #True any 와는 반대로 Iteration 을 해서 그 내용은 모두 참이어야 참이라는 것을 나타냅니다. 2022. 5. 17.
operator의 itemgetter를 사용해서 리스트 정렬 함수형 프로그램을 위한 패키지중 operator모듈의 itemgetter를 사용해서 리스트를 정렬하는 예제 1. 튜플의 리스트를 생성 2. itemgetter를 import 3. 정렬에 itemgetter를 지정 아래 예제는 item의 배열1번째를 기준으로 정렬을 의미....여기 예제에서는 31/32/34/23/3의 정렬기준으로 데이터를 출력 data = [ ("hansj", 31, 111), ("kim", 32, 222), ("an", 34, 666), ("bang", 23, 444), ("jin", 3, 333), ] from operator import itemgetter for name in sorted(data, key=itemgetter(1)): print(name) print() for na.. 2022. 5. 17.
collections 모듈 - OrderedDict 1. OrederedDict 란? OrderedDict 는 기본 딕셔너리(dictionary)와 거의 비슷하지만, 입력된 아이템들(items)의 순서를 기억하는 Dictionary 클래스 # 예제1 - sorted()를 이용한 정렬된 OrderedDict 만들기 from collections import OrderedDict # 기본 딕셔너리 d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange':2} # 키(key)를 기준으로 정렬한 OrderedDict ordered_d1 = OrderedDict(sorted(d.items(), key=lambda t:t[0])) print(ordered_d1) ''' 결과 OrderedDict([('apple', 4), ('bana.. 2022. 5. 12.
collections 모듈 - namedtuple # 예제1. tuple() vs namedtuple() # tuple() a = ('John', 28, '남') b = ('Sally', 24, '여') for n in [a, b]: print('%s은(는) %d 세의 %s성 입니다.' %n) ''' 결과 John은(는) 28 세의 남성 입니다. Sally은(는) 24 세의 여성 입니다. ''' import collections # namedtuple() Person = collections.namedtuple("Person", 'name age gender') P1 = Person(name='Jhon', age=28, gender='남') P2 = Person(name='Sally', age=28, gender='여') for n in [P1, P2].. 2022. 5. 12.
collections 모듈 - deque 1. deque란 Deque(데크)는 double-ended queue 의 줄임말로, 앞과 뒤에서 즉, 양방향에서 데이터를 처리할 수 있는 queue형 자료구조를 의미한다. 아래의 [그림1]은 deque의 구조를 나타낸 그림이다. python 에서 collections.deque는 list와 비슷하다. append(), pop() 등의 메소드를 deque에서도 제공한다 append(x) list.append(x) 와 마찬가지로 x를 deque의 오른쪽(마지막)에 추가(삽입)해준다. # 예제1. list.append() vs deque.append() import collections # list lst = ['a', 'b', 'c'] lst.append('d') print(lst) ''' 결과 ['a',.. 2022. 5. 12.
collections 모듈 - defaultdict # 예제(1) - dict vs defaultdict # 1-1. 기본 딕셔너리 import collections ex1 = {'a':1, 'b':2} print(ex1) ------------------------- print(ex1['c']) ''' 결과 {'b': 2, 'a': 1} --------------------------------- # defaultdict의 초기값 생성 KeyError: 'c' ''' # 1-2. collections.defaultdict # defaultdict의 초기값 생성 def default_factory(): return 'null' ex2 = collections.defaultdict(default_factory, a=1, b=2) print(ex2) prin.. 2022. 5. 12.