Python 내장함수

Nicholas·2022년 4월 23일
0

Python

목록 보기
25/31
post-thumbnail

1. 내장함수란?

  • 파이썬 라이브러리안에 기본적으로 내장되어있는 함수를 말한다.
  • 외부 패키지에 있는 함수를 불러올땐 improt과정이 필요했지만 내장함수는 필요없다.

2. 대표적인 내장함수(dir)

  • 각 객체가 가지고있는 변수나 함수들을 보여준다.
print(dir({'1': 'abc'})) # 딕셔너리에서 가지고 있는 함수들 내역

"내장함수.py"
['__class__', '__class_getitem__', '__contains__','__delattr__', 
'__delitem__','__dir__', '__doc__','__eq__', '__format__','__ge__',
'__getattribute__','__getitem__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__ior__', '__iter__', '__le__','__len__', 
'__lt__', '__ne__', '__new__', '__or__', '__reduce__', 
'__reduce_ex__', '__repr__','__reversed__','__ror__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear',
'copy','fromkeys','get', 'items', 'keys', 'pop', 'popitem', 
'setdefault','update', 'values']
print(dir("python")) # 문자열에서 가지고 있는 함수들 내역

"내장함수복습.py"
['__add__', '__class__', '__contains__', '__delattr__','__dir__', 
'__doc__','__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', 
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', 
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 
'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 
'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 
'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 
'rsplit', 'rstrip', 'split', 'splitlines', 
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 
'zfill']

3. map & filter

  • iterator객체(나열되어있는 구조를가진 객체)를 조작할때 사용한다.
  • iterator객체 : list, tuple, string
  • map/filter 함수는 자체적으로 받은 객체를 하나씩 돌려주기때문에 받을 객체의 형태를 지정해주지 않는다면,<map/filter object at. 0x108ad2500>(의미: 형식없음) 오류가 발생한다.

3-1. map함수

  • iterator객체들의 내부 인자들을 일일이 변경할때 사용한다.
  • 기본구조 map(함수명, 객체명), 나열식 객체들을 함수로 하나씩 돌려준다.
def add(a):
    return a * 3


li = [1, 2, 3]
print(list(map(add, li)))
print(tuple(map(add, li)))

>>> [3, 6, 9]
    (3, 6, 9)
    
li2 = list(map(add, li))
print(li2)

>>> [3, 6, 9]

3-2. filter함수

  • interator 객채의 요소중 원하는(함수로)요소들만 걸러줄때 사용
  • 기본구조 : filer(함수명, 객체명)
li = [1, 2, 3, 4, 5]


def filtering(a):
    if a % 2 == 0:
        return True
    return False


print(list(filter(filtering, li)))
print(tuple(filter(filtering, li)))

>>> [2, 4]
    (2, 4)
    
l2 = tuple(filter(filtering, li))
print(l2)

>>> (2, 4)

map이나 fliter를 쓰는이유 : 함수에 반복문을 추가해서 할수 있지만 코드의 단순화를 위해 내장함수를 사용한다.

4. zip함수

  • 동일한 갯수로 이루어진 intarator객체를 묶어주는 함수다. 이 함수도 자체적으로 받은 값을 돌려주지않기 때문에 객체의 형태를 지정하는 함수를 동반해야한다.
a = [4, 5, 6]
b = ['d', 'e', 'f']
li = list(zip(a, b))
print(li)

>>> [(4, 'd'), (5, 'e'), (6, 'f')]

print(list(zip([1, 2, 3], [4, 5, 6])))
print(list(zip([1, 2, 3], ['a', 'b', 'c'])))

>>> [(1, 4), (2, 5), (3, 6)]
    [(1, 'a'), (2, 'b'), (3, 'c')]

5. 기타 많이쓰이는 내장함수

  • input : 사용자 입력값을 받는 함수
  • open : 파일을 만들고 쓰고 내용을 추가하고 읽을 때 사용, 함수편(사용자 입력과 출력편)참고
  • print : 모니터화면에 결과값을 출력해준다
  • pow : 제곱해준다
  • range : for문과 함께 많이 사용하는 함수로 해당 입력값의 범위값을 intarator객체로 돌려준다.
  • list : 리스트로 변환해준다.
  • tuple : 튜플로 변환해준다.
  • type : 객체의 자료형이 무엇인지 알려주는 함수.
profile
WEB Developer

0개의 댓글