-
[python] 파이썬 데이터 분석 입문 - 리스트, 튜플, 딕셔너리코딩 연습/코딩배우기 2020. 10. 9. 20:29반응형
■ 리스트, 튜플, 딕셔너리 관련 함수 등 정리
a = [2, 4, 6] a.append(8) print(a) # [2, 4, 6, 8] --> 요소 추가 a.extend([10, 12]) print(a) # [2, 4, 6, 8, 10, 12] --> 리스트 확장 b = a.pop() print(a, ' : ', b) # [2, 4, 6, 8, 10] : 12 --> 삭제 및 삭제 값 반환 b = a.pop(1) print(a, ' : ', b) # [2, 6, 8, 10] : 4 --> index 지정 삭제 가능 a.remove(10) print(a) # [2, 6, 8] --> 삭제할 요소(값) 지정하여 삭제
■ reverse() 함수는 기존(원본) 리스트를 반전시킴. 기존 리스트를 변경하지 않으려면 사본 생성 후 이용해야 함
a_list = [1, 2, 3, 4, 5] r_list = a_list[:] # 복사(사본 생성) print(r_list) # [1, 2, 3, 4, 5] r_list.reverse() print(r_list) # [5, 4, 3, 2, 1] print(a_list) # [1, 2, 3, 4, 5] # sort() 함수도 기존 리스트를 변경시킴 unordered_list = [3, 5, 1, 7, 2] unordered_list.sort() print(unordered_list) # [1, 2, 3, 5, 7]
■ sorted() 함수로 특정 위치에 따라 리스트 정렬하기
my_list = [[1, 2, 3, 4], [4, 3, 2, 1], [2, 4, 1, 3]] sorted_by_index_3 = sorted(my_list, key = lambda index_value: index_value[3]) print(my_list) # [[1, 2, 3, 4], [4, 3, 2, 1], [2, 4, 1, 3]] print(sorted_by_index_3) # [[4, 3, 2, 1], [2, 4, 1, 3], [1, 2, 3, 4]]
sorted()는 원본 리스트를 변경하는 것이 아니라 새로운 리스트를 반환하며,
sorted() 함수를 key 함수와 결합하여 각 리스트의 특정 인덱스 값으로 정렬할 수 있다.■ 리스트, 튜플, 딕셔너리를 다양한 기준에 따라 정렬하는 operator 모듈(operator의 itemgetter() 함수 이용)
from operator import itemgetter my_lists = [[122, 3, 3, 444], [22, 6, 6, 444], [354, 4, 4, 678]] my_lists_index_3_and_0 = sorted(my_lists, key = itemgetter(3, 0)) print(my_lists_index_3_and_0) # [[22, 6, 6, 444], [122, 3, 3, 444], [354, 4, 4, 678]] # 3번째 index 값 정렬 후 0번째 index 값으로 정렬
■ 튜플(tuple)
- 값 변경(추가, 수정, 삭제) 불가하다는 것만 제외하면 리스트와 유사함
my_tup1 = ('x', 'y', 'z') my_tup2 = 'x,', 'y', 'z' my_tup3 = (10,) my_tup4 = 10, print(type(my_tup1), id(my_tup1)) # <class 'tuple'> 2103985191360 print(type(my_tup2), id(my_tup2)) # <class 'tuple'> 2104002165568 print(type(my_tup3), id(my_tup3)) # <class 'tuple'> 2104002321808 print(type(my_tup4), id(my_tup4)) # <class 'tuple'> 2104002321808 print(my_tup3 is my_tup4) # True one, two, three = my_tup1 # tuple unpacking print(one, two, three) # x y z # tuple 값 변경 my_tup5 = (1, 2, 3) print(id(my_tup5)) #my_tup5.append(4) # AttributeError: 'tuple' object has no attribute 'append' my_list = list(my_tup5) print(type(my_list)) # <class 'list'> my_list.append(4) my_tup5 = tuple(my_list) print(my_tup5, type(my_tup5), id(my_tup5)) # (1, 2, 3, 4) <class 'tuple'> 2103889798624 # 변수명만 같은 다른 튜플이 생성됨
■ 딕셔너리(dict)
- 리스트는 index로 개별 값에 접근하고, 정렬되어있지만,
- 딕셔너리는 index가 없고, key(키)가 있는데 이 키에는 정수, 문자열, 기타 파이썬 객체를 사용하여 개별 값에 접근할 수 있고, 정렬되어있지않다.
- 리스트는 기존에 없는 index를 사용할 수 없지만, 딕셔너리는 새로운 key(키)를 생성할 수 있다.
empty_dict = {} a_dict = {'one': 1, 'two': 2, 'three': 3} another_dict = {'x': 'printer', 'y': 5, 'z':['star', 'circle', 9]} b_dict = dict(apple = 10, pear = 20, orange = 30) empty_dict[1] = 'one' empty_dict[2] = 'two' print(empty_dict) # {1: 'one', 2: 'two'} print(len(a_dict)) # 3 print(a_dict['two']) # 2 print(another_dict['z']) # ['star', 'circle', 9] print(another_dict['z'][1]) # circle c_dict = b_dict b_dict['pear'] = 50 print(b_dict) # {'apple': 10, 'pear': 50, 'orange': 30} print(c_dict) # {'apple': 10, 'pear': 50, 'orange': 30} d_dict = b_dict.copy() # 얕은 복사 (사본 생성) d_dict['pear'] = 60 print(b_dict) # {'apple': 10, 'pear': 50, 'orange': 30} print(d_dict) # {'apple': 10, 'pear': 60, 'orange': 30} # keys(), values(), items() # 위 함수의 반환 값은 리스트 객체가 아닌 딕셔너리 뷰 객체를 반환함 print(another_dict.keys()) # dict_keys(['x', 'y', 'z']) print(type(another_dict.keys())) # <class 'dict_keys'> print(another_dict.values()) # dict_values(['printer', 5, ['star', 'circle', 9]]) print(another_dict.items()) # dict_items([('x', 'printer'), ('y', 5), ('z', ['star', 'circle', 9])]) for i in another_dict.values(): print(i) ''' printer 5 ['star', 'circle', 9] ''' # key(키) 존재 여부 확인 print('pear' in b_dict) # True print('x' not in a_dict) # True #print(another_dict['t']) # KeyError: 't' print(another_dict.get('t')) # None print(another_dict.get('z')) ['star', 'circle', 9] # 딕셔너리 정렬하기 dict_copy1 = sorted(b_dict, key = lambda item: item[0]) print(dict_copy1) # ['apple', 'orange', 'pear'] --> a, o, p dict_copy1 = sorted(b_dict, key = lambda item: item[1]) print(dict_copy1) # ['pear', 'apple', 'orange'] --> e, p, r
[참고] Foundations for Analytics with Python - 파이썬 데이터 분석 입문
반응형'코딩 연습 > 코딩배우기' 카테고리의 다른 글
[python] 파이썬 파일 처리 - 명령 프롬프트에서 파일명 읽어 실행하기 (0) 2020.10.11 [python] 파이썬 예외처리 (0) 2020.10.11 [python] dict 연습 - 단어(문장)에서 모음 찾기 (0) 2020.10.08 [python] 파이썬에서 환경 변수 읽어오기, 현재 작업 디렉토리 등 (0) 2020.10.08 [python] 파이썬 정규 표현식 (regular expression) (0) 2020.09.27