코테에서 자주 사용하는 라이브러리,함수 모음 (계속 추가 예정)
1. enumerate
반복문에서 인덱스 번호가 필요할 때 사용한다. (index, 리스트에서 그 인덱스에 해당하는 값) 형태로 반환
chs = ["a","b","c"]
for pair in enumerate(chs):
print(pair)
출력값
(0,"a")
(1,"b")
(2,"c")
2. 순열, 조합 (경우의 수 문제에서 사용)
from itertools import combinations (조합)
combinationList = list(combination(리스트변수, 조합할 개수))
from itertools import permutations (순열)
permutationList = list(permutation(리스트변수, 순열만들 수의 개수))
from itertools import product (중복 순열)
productList = list(product(리스트변수, repeat=개수))
3. map
4. zip
zip()함수는 파라미터로 들어온 리스트들에 인덱스가 맞는 아이들끼리 튜플을 만들어 준다.
numbers = [1,2,3]
chs = ["a","b","c"]
zip(numbers,chs)
반환 값은 <zip object at 0x7fb23a2ac4c0> 이런식으로 뜬다... print해도 마찬가지
주로 for문에서 사용
for pair in zip(numbers,chs):
print(pair)
하면 출력값으로
(1,"a")
(2,"b")
(3,"c")
를 얻을 수 있다.
5. 정렬 할 때 단지, 오름차순 내림차순이 아니라 자신만의 정렬 기준을 정하고싶을 때 ex. 문자열의 길이 순 (람다식)
phone_book = sorted(phone_book, key=lambda x: len(x))
6. startswith, endswith
문자열에서 시작문자와 끝문자에 대한 문제일때
7. divmod(n,m)
n을 m으로 나누었을 때 몫과 나머지를 튜플의 형태로 반환해준다.
8. int(string, base)
n진수 -> 10진수
base진법으로 표현된 string 숫자를 10진수로 바꿔 준다.
** 10진수 -> 2진수, 8진수, 6진수
bin(number)
oct(number)
hex(number)
9. reverse와 reversed
reverse는 list 함수
number = [1,2,3,4,5]
number.reverse() 는 따로 반환하는 게 없다 #number배열 자체를 바꾼다
print(number)
[5,4,3,2,1]
reversed는 문자열에서 사용가능
reversed("abcde")하면
"edcba" 리턴
10. strip(문자)
문자열.strip('문자') 는 문자열의 양옆에 '문자'를 제거
11. 2차원 배열을 transpose 하는 방법 (zip을 통해)
mylist = list(map(list, zip(*mylist)))
또는
중첩 list comprehension으로 가능
12. set 연산자
합집합 set1 | set2
교집합 set1 & set2
차집합 set1 - set2