Programming Language/Python
[Python] list, dict 자료형
DEV_HEO
2023. 3. 9. 16:58
320x100
1. list
선언
- 빈 리스트 만들기
list = []
list = list()
- 정해진 범위로 리스트 만들기
list = list(range(0, 10))
- 크기가 정해진 리스트 만들기
list = [0 for i in range(n)] # 모두 0으로
관련 메소드
- list.append(n) : 추가하기
- list.remove(n) : 제거하기. 가장 앞에 있는 n 제거
- list.sort(key = None, reversed = False) : 정렬하기
- list.clear() : 초기화하기 ( list = []와 동일)
중복 없는 리스트 만들기
-> set() 사용
list = [1, 1, 1]
list = set(list)
2. dict
선언
- 빈 dict 만들기
dict = dict()
dict = {}
- 특정 값으로 선언
dict = {"id": "abcd", "pw": "qwer"}
dict = dict({"id": "abcd", "pw": "qwer"})
dict = dict([("id","abcd"), ("pw", "qwer")])
dict = dict(id="abcd", pw="qwer")
추가하기( " 이 아니라 '임 주의)
dict['address'] = "서울"
삭제하기
del dict['address']
list를 dict로 변환하기 ( https://security-nanglam.tistory.com/427 참고)
num_list = [1, 2, 3]
id_list = ["a", "b", "c"]
dict = {id: i for i,id in enumerate(id_list)} # ==> {'a':0, 'b':1, 'c':2}
dict = {id: 0 for id in id_list} # ==> {'a':0, 'b':0, 'c':0}
dict = dict.fromkeys(id_list,0) # ==> {'a':0, 'b':0, 'c':0}
dict = dict.fromkeys(id_list) # ==> {'a':None, 'b':None, 'c':None}
dict = dict(zip(num_list, id_list)) # ==> {'a':1, 'b':2, 'c':3}
dict = dict(zip(id_list, num_list)) # ==> {1:'a', 2:'b', 3:'c'}
# tuple -> dict
tuple_list = [('a',1), ('b',2), ('c',3)]
dict = dict(tuple_list) # ==> {'a':1, 'b':2, 'c':3}
320x100