LinkedNestBlog

Python : 자료구조

by 이진원Dev
Python : 자료구조


ref. : https://wikidocs.net/68

파이썬의 자료형
>>> type('a')
<type 'str'>   # 문자열
>>> type(6)
<type 'int'>   # 정수
>>> type(3.0)
<type 'float'> # 소수
>>> type(3+6j)
<type 'complex'>   # 복소수
>>> type([1,2,3,4,5,6,7])
<type 'list'>      # 목록
자료형의 종류
1. 수치형 (numbers)
1.1. 정수(int)
1.2. 더 큰 정수(long int)
1.3. 소수short)
2. 순서형 (sequence)
2.1. 문자열(string)
2.2. 리스트(list)
2.3. 튜플(tuple)
2.4. 사용자 정의 클래스
3. 매핑형 (mapping)
3.1. 사전(dictionary)
3.2. 클래스 인스턴스
3.3. C 확장형 

문자열(string)
# >>> x = 'baseball'
# >>> x[0]
# 'b'
# >>> x[2:5]
# 'seb'
# >>> x[2:10]
# 'seball'
# >>> x[2:12]
# 'seball'
# >>> x[:3]
# 'bas'
# >>> x[:5]
# 'baseb'
# >>> x[:3]
# 'bas'
# >>> x[3:]
# 'eball'
# >>> x[5:]
# 'all'
# >>> x[10:]
# ''
# >>> x[1:]
# 'aseball'
목록
# >>> test_list = [1,3,9,10,12]
# >>> test_list.append(15)
# >>> test_list
# [1, 3, 9, 10, 12, 15]
# >>> test_list.append(16,19)
# Traceback (most recent call last):
#   File "", line 1, in 
# TypeError: append() takes exactly one argument (2 given)
# >>>
# >>>
# >>> test_list.append(8)
# >>> test_list
# [1, 3, 9, 10, 12, 15, 8]
# >>> test_list.sort()
# >>> test_list
# [1, 3, 8, 9, 10, 12, 15]
# >>> del test_list[9,12]
# Traceback (most recent call last):
#   File "", line 1, in 
# TypeError: list indices must be integers, not tuple
# >>> del test_list[0]
# >>> test_list
# [3, 8, 9, 10, 12, 15]
# >>> test_list[1] = 4
# >>> test_list
# [3, 4, 9, 10, 12, 15]
# >>>
# >>>
# >>> fastfood = ['potato',['hamburger', 'Cola', 'chips'], 'vegatables', 'chicken']
# >>> fastfood[1]
# ['hamburger', 'Cola', 'chips']
# >>> fastfood[1][3]
# Traceback (most recent call last):
#   File "", line 1, in 
# IndexError: list index out of range
# >>> fastfood[1][0]
# 'hamburger'
튜플(tuple) 일반적인 변수 값 치환
>>> a = 10
>>> b = 20
>>> temp = a
>>> a = b
>>> b = temp
>>> print a,b
20 10
Tuple의 적용
>>> c = 10
>>> d = 20
>>> c, d = d, c
>>> print c,d
20 10
예제
>>> def magu_p(x,y,*rest):
...     print x,y,rest
... 
>>> magu_p(1,2,3,4,5,6,7,8,9,10)
1 2 (3, 4, 5, 6, 7, 8, 9, 10)
튜플을 리스트로
>>> p = (1,2,3,4,5)
>>> q = list(p)
>>> print q
[1, 2, 3, 4, 5]
리스트를 튜플로
>>> r = tuple(q)
>>> print r
(1, 2, 3, 4, 5)
Python : 자료구조 · LinkedNest Blog