[Python] 자료형

LILO Ghim·2021년 11월 7일
0
post-thumbnail

list vs tuple

list와 tuple은 기본적으로 list와 같은 형태를 가지며, 표시하는 기호만 다르게 생겼다.

my_list = [1, 2, 3]
my_tuple = (1, 2, 3)

이 둘의 차이점은, 앞 포스트에서도 언급을 했지만, list는 인덱싱으로 수정이 가능하나, tuple은 변경이 되지 않는다(append() 사용이 안됨)

따라서 tuple은 메모리 사용이 적기 때문에, 데이터의 종류에 맞게 활용이 가능하다.

dictionary를 items()로 불러오면, list안에 tuple이 있는 형태로 키-값 쌍을 보여준다.

 
 my_dict = {'a' : '1', 'b' : '2', 'c':'3'}
	print(my_dict.items())

 dict_items([('a', '1'), ('b', '2'), ('c', '3')])
 

dictionary 자체로는 sort를 사용하여 오름차순 정리가 불가능하지만, tuple로 이루어진 list를 변환하여 sort를 적용하는데, 이 때는 variable.sort()가 아닌 sorted(variable.items())를 사용한다.

my_dict = {'b' : '2', 'c':'3', 'a' : '1'}
print(my_dict.items())
sorted_dict = sorted(my_dict.items())

print(sorted_dict)

#결과
dict_items([('b', '2'), ('c', '3'), ('a', '1')])
[('a', '1'), ('b', '2'), ('c', '3')]




### dictionary의 값을 수정해보기



my_dict = {'b' : '2', 'c':'3', 'a' : '1'} # origin data
print(my_dict)

tmp = list()
for key, value in my_dict.items(): #item 형태로 출력하면 tuple로 나옴 list에 추가
 tmp.append((key, value))       #list에 추가
print(tmp)

tmpreverse = list()
for key, value in my_dict.items():
 tmpreverse.append((value, key)) #key, value를 전환
print(tmpreverse)

sorted_dictionary = sorted(tmpreverse)  #tuple를 sorted로 정렬
print(sorted_dictionary)

sorted_dictionary_reverse = sorted(tmpreverse, reverse = True) #내림차순 정렬
print(sorted_dictionary_reverse)


[('b', '2'), ('c', '3'), ('a', '1')]
[('2', 'b'), ('3', 'c'), ('1', 'a')]
[('1', 'a'), ('2', 'b'), ('3', 'c')]
[('3', 'c'), ('2', 'b'), ('1', 'a')]

->dictionary를 tuple이 요소인 list로 만들고 수정하는 방법

SET

set는 중복값을 제거해주고, 순서가 없음.

a = set("Hello World!")
print(a)

{'e', 'l', '!', 'o', 'W', 'd', ' ', 'r', 'H'}
  • a.add(value)

  • a.update([]) : list나 Tuple과 같은 자료형의 데이터 추가

  • a.remove(value) : 값이 없으면 error 발생

  • a.discard(value) : 값이 있는 경우에만 삭제

  • a.pop() : 제일 앞쪽 값부터 삭제


**인덱싱

list와 Tuple은 순서가 있음으로 인덱스 값을 통해 접근 할 수 있지만, Set는 Dictionary와 비슷하게 순서가 없는 자료형임으로 인덱싱을 지원하지 않음

profile
킴릴로

0개의 댓글