파이썬은 모든 것이 클래스이다.
따라서, 여러 자료구조들 간에 형변환이 가능하다.
1. 리스트
# 리스트 - [] 연산자로 묶어서 정의 >> colors = ['red', 'green', 'gold'] >> colors ['red', 'green', 'gold'] >> type(colors) # type()은 인자로 준 자료형이 무엇인지 반환하는 함수# 리스트 - 값 추가 >> colors.append('blue') >> colors ['red', 'green', 'gold', 'blue'] >> colors.insert(1, 'black') >> colors ['red', 'black', 'green', 'gold', 'blue'] >> colors.extend(['white', 'gray']) >> colors ['red', 'black', 'green', 'gold', 'blue', 'white', 'gray'] >> colors += ['red'] >> colors ['red', 'black', 'green', 'gold', 'blue', 'white', 'gray', 'red'] >> colors += 'red' ['red', 'black', 'green', 'gold', 'blue', 'white', 'gray', 'red', 'r', 'e', 'd'] # 리스트 - index() >> colors.index('red') 0 >> colors.index('red', 1) # 시작점 명시 (순차 탐색인듯) 7 # 리스트 - 그외 >> colors.count('red') 2 >> colors.pop() # 뒤에서 값을 뽑아내고 삭제 'red' >> colors.pop(1) # index로 pop() 'black' >> colors.remove('gold') # 해당 값 삭제, 2개 있다면 앞 쪽에 있는 값 삭제 # 리스트 - 정렬 >> colors.sort() # 순방향 정렬 >> colors.reverse() # 역방향 정렬
2. 세트
# 세트(집합) - {} 연산자로 묶어서 정의 >> a = {1, 2, 3} >> b = {3, 4, 5} >> a {1, 2, 3} >> b {3, 4, 5} >> type(a)# 세트 - 집합 연산 >> a.union(b) # 합집합('|' 연산자로도 가능 ex: a | b) {1,2,3,4,5} >> a.intersection(b) # 교집합('&' 연산자로도 가능 ex: a & b) {3} >> a - b # 차집합 {1, 2}
'프로그래밍 > Python' 카테고리의 다른 글
파이썬 - 자료형과 연산자 (0) | 2011.11.28 |
---|---|
파이썬 - 파이썬의 특징 그리고 Hello world! (0) | 2011.11.26 |
스크립트 언어 하나정도는... 파이썬! (0) | 2011.11.26 |