리스트
Lists, tuples, sets, dictionaries
- Loop and Lists
-
list는 [e1, e2, …, ek]의 형태로 순서가 유지 되는 mutable, iterable, sequence 자료형
- linearly ordered + randomly accessed by index + useful with for-loop fruits = [‘apples’, ‘oranges’, ‘apricots] change = [1, ‘monkey’, 2, …] #list of different types plants = [‘pinetree’, fruits, ‘bamboo’]#nested list
-
lists(tuples) are referencial structres
-
for element in list 형태로 매우 유용하게 사용
-
making a list elements = [] for k in range(6): elements.append(k) a = [k*k for k in range(10) if k % 2]# odds in [0, 10) genereted by list comprehension
- a = range(1, 5) #range(i, j) -> [i, j)
- a = range(1, 10, 2) #range(start, end, stop)
- a = range(10, 2) #빈 range
- list comprehension: [expr for value in iterable if condition]
-
range vs list
- a = range(5)
- type(a) # type은 class range
- b = [0, 1, 2, 3, 4]
- type(b) #b의 type은 class list
- a == b #False
- c = list(a)
- b == c #true
-
membership
- x in s: True if x is in s, else False
- x not in s: True if x is not in s, else False
-
updating list
- fruits[1] = “pears”
-
inserting a new element
- fruits.append(“banana”) #가장 뒤에 삽입
- fruits.insert(2, “banana) #fruits[2 : ]은 오른쪽으로 한칸씩 이동 후, fruits[2] = “banana
- 이론적으로 개수 제한 없이 append 가능 (dynamic-array)
-
deleting elements of lists
- del fruits[1] or fruits.remove(“pear”)
- element를 지우면 그 뒷 원소들은 한 칸씩 왼쪽으로 채워짐
-
concatenating lists
- a = b + c
- opearator overloading 이라 불림
-
repetition
- s _ 3 or 3 _ s #repeating 3 times
- data = [0] * 8 #data = [0, 0, 0, 0, 0, 0, 0, 0]
-
unpacking
- ap, or, ba = fruits #fruits의 element 수와 같은 수의 배열로 unpack 해야함.
- a, b, c, d = range(7, 11)
- q, r = divmod(a, b)
- for x, y in [(1, 2), (3, 4), (5, 6)]
- packing: dual of unpacking
- data = 2, 4, 8, 6
- return a // b, a % b
-
simultaneous assignments:
- x, y, z = 1, 2, 3 #1. packed as (1, 2, 3) 2. unpacked into x, y, z
- x, y = y, x #swap x, y
-
others
- s.append(x), s.pop() #same as push, pop of stack
- s.pop(0) #same as dequeue of a queue
- len(s), min(s), max(s)
- s.index(x) #index of the first occurrence of x in s
- s.count(x) #total number of occurrences of x in s
- s.sort(), s.sort(key=int) #sort the items in s, so no return value
- ss = sorted(s) # s is not changed, return a sorted copy
-
시간복잡도 efficiency of operations of lists(and tupes)
- len(data): O(1)
- data[j], data[j] = x: O(1)
- data.count(x): O(n)
- data.index(x): O(k+1) #k는 x의 index
- x in data: O(k+1)
- data1 == (!=, >=, …) data2: O(k+1) k는 왼쪽 index
- data[j : k]: O(k - j + 1)
- data1 + data2: O(n1 + n2)
- c*data: O(cn)
- data.append(x): O(1) #평균적으로
- data.insert(k, value): O(n - k + 1) #평균적으로
- data.pop(): O(1) #평균적으로
- del data[k], data.remove(value): O(n-k), O(n) #평균적으로
- data.sort() O(nlogn)
- more
- while 루프(same control flow as in c/c++)
- Strings: immutable data type
- 앞 뒤의 공백 제거 .strip()
- 모든 공백제거 .replace(‘ ‘, ‘’)
- whitespace 제거 ‘‘.join(.split())