데이터 구조
데이터를 일정한 기준(규칙)에 의해 모아 놓은 것
collection of data elements, structured in some way
- built-in + 확장
- Container type의 데이터 구조
1) Sequence = mapping by element position (index)
ex) List, String
2) mapping = mapping by element name (key)
ex) Dictionary
built-in Sequence (내장)
1) List
2) Tuple
3) String
4) Buffer objects
5) Xrange objects
Sequence에 대한 주요 작업
1) Indexing: 위치 [0 1 2]
2) Slicing: 범위 지정해서 추출
3) Adding: seq1 + seq2
4) Multiplying: seq1*5 (seq1 5번 반복)
5) Membership: 존재 여부 확인
List
특징: Mutable!(변경가능)
- Indexing
- Slicing
- Adding, Multiplying, membership
- List methods
1) Method = object에 관련함수
Class -> object Instance
2) object.method(arguments)
1. Indexing
[index1:index2] ; index1=inclusive vs. index2=exclusive
간단한 예제)
(1) index번호는 0부터 시작하기 때문에 정확한 index값을 얻기 위해서는 (month -1)/(day-1) 을 해주어야 한다.
(2) endings: 1(st), 2(nd), 3(rd), 4~20(th) , 21(st), 22(nd), 23(rd), 24~30(th), 31(st)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | months = ['Jan','Feb','Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] #A list with one ending for each number from 1 to 31 endings = ['st', 'nd', 'rd'] + 17 * ['th'] \ + ['st', 'nd', 'rd'] + 7 * ['th'] + ['st'] year = input('Year: ') month = input('Month (1-12): ') day = input('Day (1-31): ') month_number = int(month) day_number = int(day) # Remember to subtract 1 from month and day to get a correct index month_name = months[month_number-1] ordinal = day + endings[day_number-1] print("{}/{}, {}".format(month_name,ordinal,year)) # Year: 2015 # Month (1-12): 1 # Day (1-31): 31 # Jan/31st, 2015 | cs |
2. slicing
1 2 3 4 5 6 7 8 9 | tag = '<a herf="http://www.python.org">Python web site</a>' print(tag[9:30]) #http://www.python.org url = input('Please enter the URL: ') domain = url[:-4] print("Domain name is: " + domain) # Please enter the URL: www.naver.com # Domain name is: www.naver | cs |
[start:end:step]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(numbers[2:5]) # [3, 4, 5] print(numbers[:]) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # copy numbers2 = numbers[:] print(numbers2) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #[start:end:step] print(numbers[0:10:1]) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(numbers[0:10:2]) # [1, 3, 5, 7, 9] print(numbers[::2]) # [1, 3, 5, 6, 7] print(numbers[3:6]) # [4, 5, 6] print(numbers[3:6:3]) # [4] print(numbers[::3]) # [1, 4, 7, 10] #-가 붙으면 거꾸 print(numbers[10:0:-2]) # [10, 8, 6, 4, 2] print(numbers[:5:-1]) # [10, 9, 8, 7] print(numbers[:5:-2]) # [10. 8] | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #Add print([1, 3, 4] + [2,1]) # [1, 3, 4, 2, 1] # multiply sequence = [None] * 10 print(sequence) # [None, None, None, None, None, None, None, None, None, None] #print a sentence in a center "box" of correct width sentence = input("Sentence: ") screen_width = 80 text_width = len(sentence) box_width = text_width + 6 left_margin = (screen_width-box_width) // 2 print() print(' '*left_margin+'+' + '-'*(box_width-2)+'+') print(' '*left_margin+'| ' + ' '*text_width +' |') print(' '*left_margin+'| ' + sentence +' |') print(' '*left_margin+'| ' + ' '*text_width+' |') print(' '*left_margin+'+' + '-'*(box_width-2)+'+') # +--------+ # | | # | okay | # | | # +--------+ | cs |
4. membership
권한이나 특정 문자 등을 찾을때, 유용하다
1 2 3 4 5 6 7 | permission = 'rw' print('w' in permission) # True print('x' in permission) # False # find a spam mail subject = '$$$ Get rich now!! $$$' print('$$$' in subject) # True | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | members = [ ['albert', '1234'], ['jiyoung', '4242'], ['smith', '7524'], ['babo', '4321'] ] username = input('User name: ') pin = input('PIN code: ') if [username, pin] in members: print('Access granted') # User name: jiyoung # PIN code: 4242 # Access granted else: print('Check your User name or PIN number') # User name: babo # PIN code: 1234 # Check your User name or PIN number | cs |
5. 기타
1 2 3 4 | numbers = [1, 100, 1000, 10000] print(len(numbers)) # 4 print(max(numbers)) # 10000 print(min(numbers)) # 1 | cs |
1 2 3 4 5 6 7 8 9 | x=[1, 1, 1] print(x[1]) # 1 # in-place modification (mutable!) x[1] = 2 # 1 -> 2로 바꿈 print(x) # [1, 2, 1] # len(x) = 3이기 떄문 x[10] = 5 #IndexError: list assignment index out of range | cs |
6. List 함수
1 2 3 4 5 6 7 8 9 | # list() print(list('Hello')) # ['H', 'e', 'l', 'l', 'o'] a = list('HELLO') print(a) # ['H', 'E', 'L', 'L', 'O'] # .join print(''.join(a)) # HELLO print('!'.join(a)) # H!E!L!L!O | cs |
2) del
1 2 3 | names = ['Alice', 'Beth', 'Cecil', 'Deisy'] del names[1] print(names) #['Alice', 'Cecil', 'Deisy'] | cs |
3) assign't
1 2 3 4 5 | name = list('Perl') print(name) # ['P', 'e', 'r', 'l'] name[2:] = list('ar') # [a, r] print(name) # ['P', 'e', 'a', 'r'] | cs |
4) 함수를 이용하지 않아도 list 그 자체로도 사용이 가능하긴 하다
1 2 3 4 5 6 7 | numbers = [1, 5] numbers[1:1] = [2, 3, 4, 6] print(numbers) # [1, 2, 3, 4, 6, 5] # del() numbers[1:3] = [] print(numbers) # [1, 4, 6, 5] | cs |
5) append()
1 2 3 4 | # append() lst = [1, 2, 3] lst.append(5) print(lst) # [1, 2, 3, 5] | cs |
6) count()
1 2 3 4 5 6 7 | # count() sen = ['I', 'L', 'O', 'V', 'E', 'Y', 'O', 'U'] print(sen.count('O')) #2 # """ """.count(' ') x = [[1, 2], 1, 1, [2, 1, [1, 2]]]] print(x.count(1)) # 2 | cs |
7) extend()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # extend() a = [1, 2, 3] b = [3, 2, 1] a.extend(b) print(a) # [1, 2, 3, 3, 2, 1] # vs. concatenate a = [1, 2, 3] b = [4, 5, 6] print(a+b) # 합쳐진 형태가 만들어 print(a) # but, a는 변형되지 않음 a = a + b # 합쳐진 결과를 a에 다시 저장하면 a 변형 print(a) # [1, 2, 3, 4, 5, 6] # a뒤에 b추가되는 형 a[len(a):] = b print(a) # [1, 2, 3, 4, 5, 6, 4, 5, 6] | cs |
1 2 3 4 5 | # index() heroes = ['we', 'are', 'the', 'heroes', 'who', 'say', 'of', 'course'] print(heroes.index('who')) #4 print(heroes.index('heroes')) #3 print(heroes.index('what')) #ValueError: 'what' is not in list | cs |
9) insert()
1 2 3 4 5 6 7 8 9 | # insert() numbers = [1, 2, 3, 4, 5, 7] numbers.insert(3, 'five') print(numbers) # [1, 2, 3, 'five', 4, 5, 7] numbers = [1, 2, 3, 4, 5, 7] numbers[3:3] = ['five'] print(numbers) # [1, 2, 3, 'five', 4, 5, 7] | cs |
10) pop(), remove()
1 2 3 4 5 6 7 8 9 10 11 12 13 | # pop() x = [1, 2, 3] print(x.pop()) #3 print(x) # [1, 2] print(x.pop()) #2 print(x) # [1] print(x.pop()) #1 print(x) # [] #remove() heroes = ['we', 'are', 'the', 'heroes', '!'] heroes.remove('!') print(heroes) # ['we', 'are', 'the', 'heroes'] | cs |
11) reverse()
1 2 3 4 5 6 7 | # reverse() heroes = ['we', 'are', 'the', 'heroes', '!'] heroes.reverse() print(heroes) # ['!', 'heroes', 'the', 'are', 'we'] heroes.reverse() print(heroes) # ['we', 'are', 'the', 'heroes', '!'] |
reversed()와는 다름
1 2 | # reversed() print(list(reversed(heroes))) # ['!', 'heroes', 'the', 'are', 'we'] | cs |
12) sort()
1 2 3 4 5 6 7 | # sort() x = [1, 3, 4, 5, 12, 15] y = x.sort() print(y) # None x.sort() print(x) # [1, 3, 4, 5, 12, 15] | cs |
*주의*
sort()된 값을 바로 저장할 수 없다.
값을 저장하려면 2가지 방법을 이용할 수 있다.
1 2 3 4 5 6 7 8 9 | # 저장 ver.1 x = [1, 3, 4, 5, 12, 15] y = x y.sort() print(y) # [1, 3, 4, 5, 12, 15] # 저장 ver.2 y = sorted(x) print(y) # [1, 3, 4, 5, 12, 15] | cs |
*주의2* sorted()는 항상 list를 반환된다.
1 | print(sorted('python')) # ['h', 'n', 'o', 'p', 't', 'y'] | cs |
*고급 sorting : https://wiki.python.org/HowTo/Sorting
'Data > python·알고리즘' 카테고리의 다른 글
[python 기초] python의 String에 대하여 (0) | 2018.06.27 |
---|---|
[python 기초] python의 tuple에 대하여 (0) | 2018.06.27 |
[python 기초] 데이터 타입과 변수 (0) | 2018.06.26 |
[python 기초] python 개요와 설치 (0) | 2018.06.26 |
[퀵 정렬] quick sort - python (0) | 2018.06.19 |
댓글