코테공부
Python 코테 기본 문법
아너
2024. 11. 18. 16:53
1. filter
1.1 filter 메소드
nums=[3,4,6,5,9]
odd=list(filter(lambda n: n % 2 != 0,nums))
print(odd) #[3,5,9]
* lambda함수 구조 파라미터1, 파라미터2 ...: 함수 실행 구문
1.2 list comprehension 메소드
nums=[3,4,6,5,9]
odd = [n for n in nums if n%2 != 0]
print(odd) #[3,5,9]
번외) for 문
#1 기본 for
arr=[i for i in range(5)]
print(arr) #[0, 1, 2, 3, 4]
nums=[1,2,3,4,5]
for i in nums:
print(i) #요소 한개씩 출력
#2 for문 with 딕셔너리
obj = {0:"key0", 5:"key5", 2:"key50", 3:"key3"}
for key in obj:
print(key) #key 차례대로 출력
for key in obj:
print(obj[key]) #value 차례대로 출력
#key기준 정렬
sortedArr=sorted(obj.items())
print(sortedArr) #[(0, 'key0'), (2, 'key50'), (3, 'key3'), (5, 'key5')]
#value기준 정렬
sortedArr=sorted(obj.items(),key=lambda n: n[1])
print(sortedArr) # [(0, 'key0'), (3, 'key3'), (5, 'key5'), (2, 'key50')]
주목할 점: 딕셔너리를 정렬할 경우 (튜플)리스트 형태로 반환됨. key값에 따른 밸류 조회 불가
2. reduce
reduce(함수, 시퀀스) : 시퀀스의 원소들을 누적으로 함수에 적용
from functools import reduce
#reduce(함수, 시퀀스) : 시퀀스의 원소들을 누적으로 함수에 적용
#시퀀스란 문자열, 리스트, 튜플 등
result=reduce(lambda n,m: n+m, [0,1,2,3,4])
print(result) #10
문자열 거꾸로 뒤집을 때도 사용 가능
from functools import reduce
#reduce(함수, 시퀀스) : 시퀀스의 원소들을 누적으로 함수에 적용
#시퀀스란 문자열, 리스트, 튜플 등
result=reduce(lambda n,m: m+n, "abcd")
print(result)
3. 문자열과 숫자
I=100
print(I+1) #101
print(str(I)+"1") #1001
#각 자리 숫자 더하기
#map(func,iterable)
ans=sum(map(int,str(I)))
print(ans) #1
print(list(map(int,str(I)))) #[1, 0, 0]
#특정 원소 제거
myarr=[1,2,3,4,5,6,7]
remove_set=[3,4,5]
newarr=[n for n in myarr if n not in remove_set]
print(newarr) #[1, 2, 6, 7]
4. Set
5. 조합/순열
combinations/combinations_with_replacement/permutations/product(iter,repeat=숫자)
from itertools import *
myarr=[1,2,3,4,5,6,7]
#조합 combinations
print(list(combinations(myarr,2))) #7C2
print(len(list(combinations(myarr,2)))) #21
#순열 permutations
print(list(permutations(myarr,2))) #7P2
print(len(list(permutations(myarr,2)))) #42
#중복 조합 combinations_with_replacement(교체 가능한 조합으로 외우기)
print(list(combinations_with_replacement(myarr,2))) #7H2
print(len(list(combinations_with_replacement(myarr,2)))) #28
#중복 순열 Product
print(list(product(myarr,repeat=2))) #7π2
print(len(list(product(myarr,repeat=2)))) #49
+ 모듈 내 메소드 기억 안날 때
import itertools # itertools 모듈 전체 import => method사용 시, itertools.combinations()
import collections
print(dir(itertools))
# ['__doc__', '__loader__', '__name__', '__package__', '__spec__', '_grouper',
# '_tee', '_tee_dataobject', 'accumulate', 'chain', 'combinations',
# 'combinations_with_replacement', 'compress', 'count', 'cycle', 'dropwhile',
# 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat',
# 'starmap', 'takewhile', 'tee', 'zip_longest']
#그 다음 from,import 사용 주의
from itertools import combinations #itertools 모듈에서 combinations만 import