DATETIME¶
In [ ]:
from datetime import datetime, date, time
dt = datetime(2011, 10, 29, 20 , 30 , 21)
dt.day
Out[ ]:
30
In [ ]:
dt.minute
Out[ ]:
30
In [ ]:
dt.date()
#스트링 변환 포맷규칙 다양하게있음
dt.strftime('%Y-%d-%m %h:%m')
Out[ ]:
'2011-29-10 Oct:10'
In [ ]:
dt.strftime('%D')
Out[ ]:
'10/29/11'
Range¶
In [ ]:
range(10)
Out[ ]:
range(0, 10)
In [ ]:
list(range(10))
Out[ ]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [ ]:
list(range(0,22,4))
Out[ ]:
[0, 4, 8, 12, 16, 20]
In [ ]:
lst = [1,2,3,4,]
for i in range(len(lst)):
temp = lst[i]
Tuple¶
In [ ]:
tup = 4,5,6
tup
Out[ ]:
(4, 5, 6)
In [ ]:
tuple([4,5,6])
Out[ ]:
(4, 5, 6)
In [ ]:
tup = tuple('abcdef')
tup[1]
Out[ ]:
'b'
In [ ]:
tup = tuple(['foo',[1,2],True])
tup
Out[ ]:
('foo', [1, 2], True)
In [ ]:
tup[0] = 'temp'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-cc3f923ed167> in <module>()
----> 1 tup[0] = 'temp'
TypeError: 'tuple' object does not support item assignment
In [ ]:
tup[1].append(3)
tup
Out[ ]:
('foo', [1, 2, 3], True)
In [ ]:
a,b,c = tup
c
Out[ ]:
True
In [ ]:
tup = 4 ,5 , (6,7)
a,b,(c,d) = tup
d
Out[ ]:
7
In [ ]:
#swap
a,b = 1, 2
b,a = a,b
a,b
Out[ ]:
(2, 1)
In [ ]:
seq = [(1,2,3,),(4,5,6,),(7,8,9,)]
for a, b, c in seq:
print('a={} b ={} c={}'.format(a,b,c))
a=1 b =2 c=3
a=4 b =5 c=6
a=7 b =8 c=9
In [ ]:
values = 1,2,3,3,3,6,7,8
a,b,*rest = values
rest
Out[ ]:
[3, 3, 3, 6, 7, 8]
In [ ]:
values.count(3)
Out[ ]:
3
LIst¶
In [ ]:
lst = ['123','tesfdf','1fiivo']
lst.append('ttttt')
lst
Out[ ]:
['123', 'tesfdf', '1fiivo', 'ttttt']
In [ ]:
lst.insert(2,'insert!')
lst
Out[ ]:
['123', 'tesfdf', 'insert!', '1fiivo', 'ttttt']
In [ ]:
#그외 pop remove 등등있음
#이런식으로 검사가능
'123' in lst
Out[ ]:
True
In [ ]:
temp = [1,2,3,4,5,]
lst+temp
Out[ ]:
['123', 'tesfdf', 'insert!', '1fiivo', 'ttttt', 1, 2, 3, 4, 5]
In [ ]:
# +는 새로운 list 만드는거라 용량 크다 따라서 lst가 너무 크면 그냥 원래거에 더하셈 ㅇㅇ
lst.extend(temp)
lst
every = []
#첫번째 방법이 두번째 더하기보다 좀 더 빠르다
for chunk in lst:
every.extend(chunk)
for chunk in lst:
every += chunk
Out[ ]:
['123', 'tesfdf', 'insert!', '1fiivo', 'ttttt', 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
In [ ]:
a = [1,6,3,4,5,10,2]
#list값이 int나 str이나 단일된 값이야지 sort가능
a.sort()
a
Out[ ]:
[1, 2, 3, 4, 5, 6, 10]
In [ ]:
#sort key 설정가능 sorted 정렬된 새로운 배열 출력 reverse=True 오름 내림차순
b = ['sadfsaf','sf','asfsd','asdfsafasdfasdf']
temp = sorted(b,key=len,reverse=True)
temp
Out[ ]:
['asdfsafasdfasdf', 'sadfsaf', 'asfsd', 'sf']
In [ ]:
sorted('abbbccddee fdafsf')
Out[ ]:
[' ',
' ',
'a',
'a',
'b',
'b',
'b',
'c',
'c',
'd',
'd',
'd',
'e',
'e',
'f',
'f',
'f',
's']
bisect¶
In [ ]:
import bisect
c = [1,2,2,2,3,4,5]
bisect.bisect(c,1)
Out[ ]:
1
In [ ]:
bisect.bisect(c,5)
Out[ ]:
7
In [ ]:
bisect.insort(c,4)
In [ ]:
c
Out[ ]:
[1, 2, 2, 2, 3, 4, 4, 5]
Slice¶
In [ ]:
# [start:end]
lst = [8,5,6,9,4,5,3,2,6]
lst[1:3]
Out[ ]:
[5, 6]
In [ ]:
#이런것도 ㄱㄴ
lst = [8,5,6,9,4,5,3,2,6]
print(lst)
lst[0:3] = [1,1,1,1]
lst
[8, 5, 6, 9, 4, 5, 3, 2, 6]
Out[ ]:
[1, 1, 1, 1, 9, 4, 5, 3, 2, 6]
In [ ]:
#생략하면 처음 or 끝
lst = [8,5,6,9,4,5,3,2,6]
print(lst[:3])
print(lst[3:])
[8, 5, 6]
[9, 4, 5, 3, 2, 6]
In [ ]:
#-는 끝에서부터 세는거
lst[-2]
Out[ ]:
2
In [ ]:
# slice 세번째는 step
lst = list(range(10))
print(lst[::2])
print(lst[::-1])
[0, 2, 4, 6, 8]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
enumerate¶
In [ ]:
for value in collection:
pass
for i, value in enumerate(collection):
pass
#이런식으로 가능
In [ ]:
lst = ['foo','bar','baz']
mapping = {}
for i,value in enumerate(lst):
mapping[value] = i
mapping
Out[ ]:
{'bar': 1, 'baz': 2, 'foo': 0}
Zip¶
In [ ]:
seq1 = ['foo','bar','baz']
seq2 = ['one','two','three']
zipped = zip(seq1,seq2)
list(zipped)
Out[ ]:
<zip at 0x7f8e3bf8e508>
In [ ]:
#긴거랑 합치면 작은거 기준으로 만들어짐
list(zip(seq1,seq2,[True,False]))
Out[ ]:
[('foo', 'one', True), ('bar', 'two', False)]
In [ ]:
for i,(a,b) in enumerate(zip(seq1,seq2)):
print('{}:{},{}'.format(i,a,b))
0:foo,one
1:bar,two
2:baz,three
reverse¶
In [ ]:
lst = [1,5,2,3,4,6,1,]
list(reversed(lst))
Out[ ]:
[1, 6, 4, 3, 2, 5, 1]
dictionary¶
In [ ]:
d1 = {'1':'abbbccc',2 : [1,2,3,4,5,6,],'5': 'stringinging'}
d1['5']
Out[ ]:
'stringinging'
In [ ]:
'1' in d1
Out[ ]:
True
In [ ]:
d1['kekekey'] = 123
d1
Out[ ]:
{'1': 'abbbccc', 2: [1, 2, 3, 4, 5, 6], '5': 'stringinging', 'kekekey': 123}
In [ ]:
del d1['1']
d1
Out[ ]:
{2: [1, 2, 3, 4, 5, 6], '5': 'stringinging', 'kekekey': 123}
In [ ]:
temp = d1.pop(2)
temp
Out[ ]:
[1, 2, 3, 4, 5, 6]
In [ ]:
#key value
print(list(d1.keys()))
print(list(d1.values()))
['5', 'kekekey']
['stringinging', 123]
In [ ]:
#dictionary combine
d1.update({23:123123,'ttee':[123,44,12,3]})
d1
Out[ ]:
{23: 123123, '5': 'stringinging', 'kekekey': 123, 'ttee': [123, 44, 12, 3]}
In [ ]:
mapping = {}
for key, value in zip(lst1,lst2):
mapping[key] = value
In [ ]:
mapping = dict(zip(range(5),reversed(range(5))))
mapping
Out[ ]:
{0: 4, 1: 3, 2: 2, 3: 1, 4: 0}
In [ ]:
if key in some_dict:
value = some_dict[key]
else:
value = default_value
# pop은 없으면 예외인데 get은 none반환함
value = some_dict.get(key,default_value)
Out[ ]:
range(0, 5)
In [ ]:
#사전에 새로운 단어를 추가하는 상황
by_letter = {}
#일반적인 상황
for word in words:
letter = word[0]
if letter not in by_letter:
by_letter[letter] = [word]
else:
by_ltter[letter].append(word)
#향상된 방법
for word in words:
letter = word[0]
by_letter.setdefault(letter,[]).append(word)
리스트 키 값은 해쉬가능한 값이어야함. 즉, 변하지않는 값 list 이런건 안됨
Set¶
In [ ]:
temp = set([1,2,2,2,3,5,5])
a = {1,2,3,4,5,}
b = {3,4,5,6,7,8}
a.union(b)
a|b
Out[ ]:
{1, 2, 3, 4, 5, 6, 7, 8}
In [ ]:
#intersection
a&b
#그외 집합연산 많음
Out[ ]:
{3, 4, 5}
In [ ]:
#이런 연산도 제공해줌
c = a.copy()
c|= b
List 표기법¶
In [ ]:
[expr for val in collection if condition]
result = []
for val in collection:
if condition:
result.append(expr)
위에 두개는 같은거임
딕셔너리도 표현가능
{key-expr:value-expr for val in collection if condition }
In [ ]:
중첩된 리스트도 표현가능
all data 중에서 e가 두개이상 들어간 이름들의 합을 생각해보자
all_data = [[이름들...],[이름들...]]
1번방법
names_of_interest = []
for names in all_data:
enough_es = [name for name in names if name.count('e') >= 2]
names_of_interest.extend(enough_es)
2번방법
[name for names in all_data for name in names if name.count('e' >= 2)]
함수¶
In [ ]:
a = []
def test():
a.append(4)
test()
print(a)
a = 3
def test():
global a = 4
test()
print(a)
왜 리스트는 global 안해도되냐?
원래 namespace에서 찾을때 지역 -> 전역 이렇게 찾는데 지역에서 없으면 전역에서 찾아서 바꿈 근데 list는 mutable이라서 변경가능하고 변수는 immutable이라서 안됨. 근데 구글링한거라 아닐수도있음
[4]
In [ ]:
#여러개 반환 가능
def f():
a, b, c = 1, 2, 3
return a, b, c
temp = f()
a,b, *rest = f()
print(a,b)
1 2
In [ ]:
#데이터 정제
#함수도 객체다 재사용성 위해 clean_ops[] 형태로 만들어서 function에 넣으면 알아서 돌아감
import re
states = ['Allbial','##Fdfsf',' dfadsf dsaf','Tooel','vieiifd?']
def remove_punctuation(value):
return re.sub('[!#?]','',value)
clean_ops = [str.strip,remove_punctuation,str.title]
def clean_strings(strings,ops):
result = []
for value in strings:
for function in ops:
value = function(value)
result.append(value)
return result
clean_strings(states,clean_ops)
Out[ ]:
['Allbial', 'Fdfsf', 'Dfadsf Dsaf', 'Tooel', 'Vieiifd']
익명함수¶
In [ ]:
def fun(x):
return x*2
temp = lambda x: x*2
In [ ]:
#람다 함수 사용하면 인자로 넘어줄때 편하다
def apply_to_list(some_list,f):
return [f(x) for x in some_list]
ints = [4,0,1,5,6]
apply_to_list(ints,lambda x:x*2)
Out[ ]:
[8, 0, 2, 10, 12]
커링¶
In [ ]:
def add_num(x,y):
return x+y
add_five = lambda y:add_number(5,y)
이터레이터¶
In [ ]:
#range(100)같은거 미리만들면 비효율적이니까 그때그때 생성함 lazy evaluation
#이터레이터는 iter을 갖고있는데 여기서 next할때마다 하나씩 뽑혀나온다.
#obj이 iter,next or getitem 갖고있으면 이터레이터 기능 가능
temp = range(100)
temp2 = temp.__iter__()
temp2.__next__()
temp2.__next__()
temp2.__next__()
temp2.__next__()
temp2.__next__()
temp2.__next__()
temp2.__next__()
temp2.__next__()
Out[ ]:
7
In [ ]:
from pprint import pprint;
dic = [1,2,3,4]
pprint(dir(dic))
a, _, c, d = range(4)
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
In [ ]:
class Counter:
def __init__(self, stop):
self.stop = stop
def __getitem__(self, index):
if index < self.stop:
return index
else:
raise IndexError
print(Counter(3)[0], Counter(3)[1], Counter(3)[2])
for i in Counter(3):
print(i, end=' ')
0 1 2
0 1 2
In [ ]:
import random
temp = iter(range(3))
print(next(temp))
print(next(temp))
print(next(temp))
#2나오면 stop하겠다는거임 ㅇㅇ
it = iter(lambda : random.randint(0, 5), 2)
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
0
1
2
0
1
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-9-8fc04bcb5b18> in <module>()
10 print(next(it))
11 print(next(it))
---> 12 print(next(it))
13 print(next(it))
14 print(next(it))
StopIteration:
In [ ]:
#iter 만들어보기
class MultipleIterator:
def __init__(self, stop, multiple):
self.stop = stop
self.multiple = multiple
self.current = 0
def __iter__(self):
return self
def __next__(self):
self.current += 1
if self.current * self.multiple < self.stop:
self.current += 1
return self.current * self.multiple
else:
raise StopIteration
for i in MultipleIterator(20, 3):
print(i, end=' ')
print()
for i in MultipleIterator(30, 5):
print(i, end=' ')
6 12 18
10 20 30
제너레이터¶
In [ ]:
# next getitem 이런거 필요없이 yeild로 iterator생성가능
dic1 = {'a':1,'b':2,'c':3}
for key in dic1:
print(key)
a
b
c
In [ ]:
def number_generator():
x = [1, 2, 3]
yield from x # 리스트에 들어있는 요소를 한 개씩 바깥으로 전달
for i in number_generator():
print(i)
1
2
3
In [ ]:
gen = (x**2 for x in range(100))
123
예외처리¶
In [ ]:
def attempt_float(x):
try:
return float(x)
except:
return x
attempt_float('123123.123123dfdfdf')
Out[ ]:
'123123.123123dfdfdf'
In [ ]:
def attempt_float(x):
try:
return float(x)
#이런식으로 에러 지정도가능
except (ValueError,TypeError):
return x
In [ ]:
f = open(path,'w')
try:
write_to_file(f)
except:
print('Failed')
else:
print('succeeded')
finally:
f.close()
파일과 운영체제¶
In [ ]:
path = 'path.txt'
f = open(path)
In [ ]:
lines = [x.rstrip() for x in open(path)]
#with block 끝나면 자동으로 파일 닫아줌
with open(path) as f:
pass