-
Python Useful FunctionsComputer Science/Basic Programming with Python 2021. 11. 20. 19:00
Python에서 다른 library를 이용하지 않고도 사용할 수 있는 유용한 함수들이 있다.
abs는 절대값을 계산해준다.
abs(-2.371) 2.371
최소값과 최대값을 반환하는 min, max함수도 있고,
min([-1, 1, 2, 3, 4]) -1
max([-1, 1, 2, 3, 4]) 4
정렬 후 결과를 주는 sorted함수도 있다.
sorted([4, -1, 5, 0, 3]) [-1, 0, 3, 4, 5]
type이 무엇인지 알려주는 type함수도 있고,
print(type(1)) print(type(0.23)) print(type('hello')) print(type([1, 2, 3, 4])) print(type((1, 2, 3, 4))) print(type({1, 2, 3, 4})) print(type({1:'one', 2:'two'}))
<class 'int'> <class 'float'> <class 'str'> <class 'list'> <class 'tuple'> <class 'set'> <class 'dict'>
반올림해 반환하는 rounda = 3.14159234 print(round(a, 3)) print(round(a))
3.142 3
x의 y 제곱을 반환하는 pow도 있다.
print(pow(2, 2)) print(pow(2, 10))
4 1024
두 리스트를 각각 짝이 맞는 숫자들을 한쌍씩으로 묶어주는 zip 함수도 있다.
list(zip([1, 2, 3, 4, 0], [5, 6, 7, 8])) [(1, 5), (2, 6), (3, 7), (4, 8)]
함수와 컬렉션을 parameter로 받아서 계산 후 리턴해주는 map 함수도 있다.
list(map(lambda x: x + 2, [1, 2, 3, 4, 5])) [3, 4, 5, 6, 7]
리스트를 만들 때, 필터를 해주는 filter 함수도 유용하다.
list(filter(lambda x : x % 2 == 0, [0, 1, 2, 3, 4])) [0, 2, 4]
이외에도 여러가지 built-in functions들이 존재한다.
'Computer Science > Basic Programming with Python' 카테고리의 다른 글
Object Oriented (0) 2021.12.07 Python Library (0) 2021.11.20 Lambda (0) 2021.11.20 Nested Function (0) 2021.11.19 Recursive Function (0) 2021.11.19