안녕세계
파이썬에서 .sort() 메서드와 built-in 함수 sorted()의 차이를 알아봅니다. .sort()list.sort([reverse=][, key=]) - 원본 리스트를 정렬하되 반환 값은 None 입니다.- 원본 리스트의 순서를 변경합니다. (원본 리스트에 영향 있음) 예제l1 = [1, 3, 2] print(l1.sort()) # None print(l1) # [1, 2, 3] sorted()sorted(iterable[, key=][, reverse=]) - 정렬된 새로운 리스트를 반환합니다. (원본 리스트에 영향 없음)- 모든 iterable에 동작합니다. (list, tuple, dict, 문자열 등) 예제l2 = [1, 3, 2] print(sorted(l2)) # [1, 2, 3] p..
파이썬 표준 라이브러리인 logging을 활용하여 로그를 남기는 방법에 대해 알아봅니다. [방법1] stream에 로그 남기기- 스트림(콘솔)에 로그를 찍기 위해 logging을 사용합니다.import logging logging.info('my INFO log') logging.warning('my WARNING log') # WARNING:root:my WARNING log위 코드를 실행하면 warning level만 출력되는 이유?- logging의 default log level이 warning으로 되어있기 때문입니다. 다음 처럼 logging의 basicConfig level을 변경하면 됩니다.import logging logging.basicConfig(level=logging.DEBUG) l..
영문 대문자와 숫자로 랜덤 문자열을 생성하는 방법을 알아봅니다. 방법import random import string print(''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)))Referenceshttps://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
list에서 dictionary 속성(property)을 검색하는 방법에 대해 알아봅니다. dicts = [ {'id': 1, 'name': 'kim', 'age': 10}, {'id': 2, 'name': 'lee', 'age': 20}, {'id': 3, 'name': 'park', 'age': 30}, {'id': 4, 'name': 'kim', 'age': 40}, ] 예제 (Python3 - 속성 검색) - 가장 먼저 검색되는 dictionary가 반환됩니다. ret = next((item for item in dicts if item['id'] == 1), None) print(ret) # {'id': 1, 'name': 'kim', 'age': 10} 예제 (Python2 - 속성 검색) -..
Object에 특정 attribute가 존재하는지 확인하는 방법을 알아봅니다. 예제class Person: name = None def __init__(self, name): self.name = name person = Person('kim') if hasattr(person, 'name'): print(person.name) # kim
파이썬 리스트의 중복을 제거하고 싶을때 1차원 리스트는 set()를 사용하면 편리하게 제거할 수 있습니다.items = [1, 2, 2, 3, 3, 3] print(set(items)) # {1, 2, 3} 이를 활용하여 2차원 리스트도 다음과 같은 방법으로 중복을 제거할 수 있습니다.items = [[1, 2], [2, 1], [1,3]] print(items) # [[1, 2], [2, 1], [1, 3]] items = list(set([tuple(set(item)) for item in item])) print(items) # [(1, 2), (1, 3)] formatted = [] for item in items: formatted.append(str(item[0], str(item[1]))) ..
count()문자 개수 세기s = 'Life is too short, You need Python' print(s.count('o')) # 5 find() 문자열에서 특정 문자 또는 문자열이 처음 나오는 인덱스를 반환합니다.만약, 찾는 문자나 문자열이 존재하지 않을 경우 -1을 반환합니다.s = 'Life is too short, You need Python' print(s.find('o')) # 9 print(s.find('x')) # -1 rfind()뒤에서 부터 시작해서 문자 또는 문자열이 처음 나오는 인덱스를 반환합니다.s = 'Life is too short, You need Python' print(s.rfind('o')) # 32 index()문자열에서 특정 문자 또는 문자열이 처음 나오는 ..
l[::], l[1:2:3], l[::-1] 처럼 index에 접근하는 방법을 extended slice라고 합니다. l[A:B:C] - index A부터 index B까지 C 간격으로 배열을 만들라는 의미 - index A가 None이면 처음부터(index가 0)이라는 의미 - index B가 None이면 마지막까지라는 의미 - index C가 None이면 하나씩이라는 의미 예제 l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(l[::2]) # 처음부터 끝까지 +두칸 간격으로 # [0, 2, 4, 6, 8] print(l[1::2]) # 인덱스 1부터 끝까지 +두칸 간격으로 # [1, 3, 5, 7, 9] print(l[::-1]) # 인덱스 마지막부터 끝까지 -한칸 간격으로 ..