본문 바로가기

Programming/Python46

index(), find() - 원소의 인덱스 index(), find() 메소드는 원소의 인덱스 위치를 반환한다 index()는 해당 원소가 없으면 ValueError를 리턴하고, find()는 -1을 리턴한다 find()는 문자열에서만 지원한다 # tuple >>> (1,2,3,4).index(2) 1 >>> (1,2,3,4).index(5) Traceback (most recent call last): File "", line 1, in ValueError: tuple.index(x): x not in tuple >>> (1,2,3,4).find(2) Traceback (most recent call last): File "", line 1, in AttributeError: 'tuple' object has no attribute 'find'.. 2020. 9. 1.
string unpacking - 문자열 언팩킹 언팩킹이란? 요소를 여러 변수에 나누어 담는 것 locals()? 현재 scope 에 있는 local 변수를 딕셔너리 type( {key:value} ) 으로 반환 >>> nums = [1,2,3,4] # unpacking >>> a,*b = nums >>> a 1 >>> b [2,3,4] >>> f'{a} {b} {nums}' 1 [2,3,4] [1,2,3,4] # unpacking >>> '{a} {b} {nums}'.format(**locals()) 1 [2,3,4] [1,2,3,4] 2020. 8. 23.
copy - shallow, deep : 깊은복사, 얕은복사 list >>> num_list = [1,2,3,4] # deep copy >>> new_list = num_list[:] >>> new_list2 = list(num_list) set >>> str_set = {'Jane', 'Tim', 'John'} # deep copy >>> new_set = str_set.copy() dict >>> str_dict = {'hi': 'world'} # deep copy >>> new_dict = str_dict.copy() use copy module >>> import copy >>> object = 'other something object' >>> new_obj = copy.copy(object) # shallow copy >>> new_obj2 = copy.. 2020. 8. 19.
generator - 제너레이터 제너레이터는 파이썬의 시퀀스를 생성하는 객체다 전체 시퀀스를 한 번에 메모리에 생성하고 정렬할 필요없이, 잠재적으로 아주 큰 시퀀스를 순회할 수 있다 제너레이터를 순회할 때마다 마지막으로 호출된 요소를 기억하고 다음 값을 반환한다 제너레이터 함수는 yield문을 사용한다 2020. 8. 18.
숫자 출력 시 width에 맞춰서 앞에 0 채우기 앞에 0을 채워서 스트링 길이를 width에 맞추기 >>> '3'.zfill(5) >>> '%05d'% 3 >>> format(3,'05') >>> '{0:05d}'.format(3) >>> '{n:05d}'.format(n=3) >>> '3'.rjust(5,'0') '00003' 2020. 7. 28.
python eval(), exec() - 문자열코드 실행 문자열로 표현된 코드를 실행할 때 사용 # eval() - 대입문 안됨 >> s = "'abc'.upper()" >> eval(s) 'ABC' >>> ss="b='abc'.upper()" >>> eval(ss) Traceback (most recent call last): File "", line 1, in File "", line 1 b='abc'.upper() ^ SyntaxError: invalid syntax # exec() - 대입문 가능 >>> exec(ss) >>> b 'ABC' 2020. 7. 17.