Python/ETC

[python] 파이썬 내장함수 (Built-in Functions)

꼰대 2021. 5. 14. 18:40

- 함수의 인자 중 Bold는 필수 인자

- print()는 가급적 생략


1. abs(n)

- 입력받은 숫자형 값을 절대값으로 반환

- 참고 : https://www.w3schools.com/python/ref_func_abs.asp

>> abs(-2.56)

2.56


2. all(iterable)

- 반복 가능한 object를 받아 요소가 모두 참이면 True, 하나라도 거짓이 있다면 False 반환

- 참고 : https://www.w3schools.com/python/ref_func_all.asp

>> list = [True, True, True]

>> all(list)

True

 

>> list = [True, True, False]

>> all(list)

False

 

>> list = []

>> all(list)

True

 

>> tuple = (0, 1, 1)

>> all(tuple)

False

 

>> dict = {0:'Computer', 1:'TV'}

>> all(dict)

False


3. any(iterable)

- 반복 가능한 object를 받아 요소가 하나라도 참이면 True, 모두 거짓이 있다면 False 반환

- 참고 : https://www.w3schools.com/python/ref_func_any.asp

>> list = [False, False, False]

>> all(list)

False

 

>> list = [True, True, False]

>> all(list)

True

 

>> list = []

>> all(list)

False


4. ascii(object)

- 문자를 입력 받아 아스키 값이 없는 문자는 \를 포함한 유니코드로 반환

- 참고 : https://www.w3schools.com/python/ref_func_ascii.asp

>> x = 'My name is 꼰대'

'My name is \uaf30\ub300'


5. bin(n)

- 정수형을 입력 받아 바이너리 값으로 반환 (0b로 시작)

- 참고 : https://www.w3schools.com/python/ref_func_bin.asp

>> bin(20)

0b10100


6. bool(object)

- Object를 입력 받아 bool형으로 반환

- 참고 : https://www.w3schools.com/python/ref_func_bool.asp

>> bool(1)

True

 

>> bool([1, 2])

True

 

>>bool(0)

False

 

* False를 반환하는 경우 : object값이 비어 있는 리스트형 ([], {}, ()), False, 0, None


7. callable(object)

- 입력 받은 인자가 호출 가능한 함수일 경우 True 반환

- 참고 : https://www.w3schools.com/python/ref_func_callable.asp

>> x = 100

>> callable(x)

False

 

>> def x():

...     a = 100

>> callable(x)

True


8. chr(number)

- 아스키 (ASCII) 코드값을 받아 그 코드에 해당하는 문자를 반환

- 참고 : https://www.w3schools.com/python/ref_func_chr.asp

- 아스키 값 참고 : https://www.easycalculation.com/ascii-hex.php

>> chr(97)

a

>> chr(48)

0


9. delattr(object, attribute)

- object와 attribute를 인자로 받아 해당 attribute를 object에서 삭제

- 참고 : https://www.w3schools.com/python/ref_func_delattr.asp

>> class Person:

    ... name = 'ggondae'

    ... age = 36

    ... contury = 'Korea'

>> pp = Person()

>> print('name attr :', hasattr(pp, 'name'))

>> print('age attr :', hasattr(pp, 'age'))

>> print('contury attr :', hasattr(pp, 'contury'))

>> delattr(Person, 'age')

>> print('name attr :', hasattr(pp, 'name'))

>> print('age attr :', hasattr(pp, 'age'))

>> print('contury attr :', hasattr(pp, 'contury'))

name attr : True
age attr : True
contury attr : True
name attr : True
age attr : False
contury attr : True


10. dict(keyword=arguments)

- key=value 형태의 인자를 받아 딕션너리로 변환하여 반환

- 참고 : https://www.w3schools.com/python/ref_func_dict.asp

>> dict = dict(name = 'ggondae', age = 36, contury = 'Korea')

>> print(dict)

{'name': 'ggondae', 'age': 36, 'contury': 'Korea'}


11. dir(object)

- object를 인자로 받아 해당 object에서 사용할 수 있는 변수 및 함수 정보를 리스트로 반환

- 참고 : https://www.w3schools.com/python/ref_func_dir.asp

>> class Person:

...     name = 'ggondae'

...     age = 36

...     contury = 'Korea'

>> pp = Person()

>> dir(pp)

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'contury', 'name']


12. divmod(dividend, divisor)

- 정수를 인자로 받아 몫과 나머지를 튜플로 반환

- 참고 : https://www.w3schools.com/python/ref_func_divmod.asp

>> div = divmod(5, 2)

>> print(div)

(2, 1)


13. enumerate(iterable, start)

- 문자열, 리스트형을 인자로 받아 index와 데이터를 튜플 형태로 반환, index는 0부터 시작하며 두번째 인자로 시작 index를 지정할 수 있음

- 참고 : https://www.w3schools.com/python/ref_func_enumerate.asp

>> x = 'apple'

>> for value in enumerate(x):

...      print(value)

(0, 'a')
(1, 'p')
(2, 'p')
(3, 'l')
(4, 'e')

 

>> x = ('apple', 'banana', 'cherry')

>> for value in enumerate(x):

...      print(value)

(0, 'apple')
(1, 'banana')
(2, 'cherry')

 

>> x = ['apple', 'banana', 'cherry']
>> for idx, value in enumerate(x, 2):
...      print('{0} : {1}'.format(idx, value))

2 : apple
3 : banana
4 : cherry


14. eval(expression, globals, locals)

- python에서 실행 가능한 단일식으로 이루어진 문자열을 인자로 받아 실행하고 결과를 반환

- 참고 : https://www.w3schools.com/python/ref_func_eval.asp

>> x = '1+1'

>> print(eval(x))

2

 

>> x = 'print(10)'

>> eval(x)

10


15. exec(object, globals, locals)

- python에서 실행 가능한 블럭 형태의 문장으로 이루어진 문자열을 인자로 받아 실행하고 결과를 반환

- 참고 : https://www.w3schools.com/python/ref_func_exec.asp

>> x = 'a=3+3\nprint(a)'

>> exec(x)

6


16. filter(function, iterable)

- 두번째 인자의 데이터 중 첫번째 인자 함수의 조건에 만족하는 데이터만 반환

- 참고 : https://www.w3schools.com/python/ref_func_filter.asp

>> user = [{'name':'goondae', 'age':20}, {'name':'min', 'age':30}, {'name':'gun', 'age':40}]

>> def limit_age(user):

...      if user['age'] >= 30:

...          return True

...      else:

...          return False

>> adults = filter(limit_age, user)

>> for x in adults:

...    print(x)

{'name': 'min', 'age': 30}
{'name': 'gun', 'age': 40}


17. float(value)

- 인자로 받은 값을 float형으로 반환

- 참고 : https://www.w3schools.com/python/ref_func_float.asp

>> float(3)

3.0

>> float('3.8')

3.8


18. format(value, format)

- 인자로 받은 첫번쨰 값을 두번째 포멧으로 변환하여 반환, format 값은 아래 링크 참고

- 참고 : https://www.w3schools.com/python/ref_func_format.asp

>> x = format(100, '>5d')

>> print('number :', x)

>> print('number :', 100)

number :   100
number : 100


19. frozenset(iterable)

- 인자로 받은 리스트형의 데이터를 수정 불가능한 형태의 리스트형으로 반환

- 참고 : https://www.w3schools.com/python/ref_func_frozenset.asp

>> mylist = ['apple', 'banana', 'cherry']

>> x = frozenset(mylist)

>> for idx, value in enumerate(x):

...      print(f'x[{idx}] = {value}')

x[0] = cherry
x[1] = banana
x[2] = apple

 

>> mylist = ['apple', 'banana', 'cherry']

>> x = frozenset(mylist)

>> for idx, value in enumerate(x):

...      print(f'x[{idx}] = {value}')

>> x[1] = 'strawberry'

Exception has occurred: TypeError

'frozenset' object does not support item assignment


20. getattr(object, attribute, default)

- 첫번째 인자로 받은 object에서 두번째 인자로 받은 attribute의 값을 반환, 세번째 인자는 만약 attrubute가 없다면 인자값 반환

- 참고 : https://www.w3schools.com/python/ref_func_getattr.asp

>> class Person:

...     name = 'ggondae'

...     age = 36

...     contury = 'Korea'

>> pp = Person()

>> x = getattr(pp, 'age')

>> print(x)

36

 

>> x = getattr(pp, 'height', 'tall')

>> print(x)

tall


21. globals(), locals()

- 현재 파일 내 global변수, local변수를 딕션너리 형태로 반환, 또한 변수 선언 가능

- 참고 : https://www.w3schools.com/python/ref_func_globals.asp

https://www.w3schools.com/python/ref_func_locals.asp

>> def varTest():

...      local_var1 = 'goondae'

...      local_var2 = 30

...      local_var = [10, 20, 30]

...      print(f'3. globals() in varTest() : {globals()}')

...      print(f'4. locals() in varTest() : {locals()}')

>> global_var1 = 'korea'

>> global_var2 = 60

>> global_var3 = (100, 200, 300)

>> print(f'1. globals() in main : {globals()}')

>> print(f'2. locals() in main : {locals()}')

>> varTest()

>> globals()['test_var'] = 50

>> print(f'5. add globals() : {globals()}')

1. globals() in main : {'__name__': '__main__', '__doc__': None, '__package__': '', 
... 중간생략 ...
'varTest': <function varTest at 0x0000025BB8C65820>, 'global_var1': 'korea', 'global_var2': 60, 'global_var3': (100, 200, 300)}
2. locals() in main : {'__name__': '__main__', '__doc__': None, '__package__': '',
... 중간생략 ...
'varTest': <function varTest at 0x0000025BB8C65820>, 'global_var1': 'korea', 'global_var2': 60, 'global_var3': (100, 200, 300)}
3. globals() in varTest() : {'__name__': '__main__', '__doc__': None, '__package__': '',
... 중간생략 ...
'varTest': <function varTest at 0x0000025BB8C65820>, 'global_var1': 'korea', 'global_var2': 60, 'global_var3': (100, 200, 300)}
4. locals() in varTest() : {'local_var1': 'goondae', 'local_var2': 30, 'local_var': [10, 20, 30]}
5. add globals() : {'__name__': '__main__', '__doc__': None, '__package__': '',
... 중간생략 ...
'varTest': <function varTest at 0x000001CBD18E5820>, 'global_var1': 'korea', 'global_var2': 60, 'global_var3': (100, 200, 300), 'test_var': 50}


22. hasattr(object, attribute)

- 첫번째 인자로 받은 object에 두번째 인자로 받은 attribute가 있으면 True, 없으면 False를 반환

- 참고 : https://www.w3schools.com/python/ref_func_hasattr.asp

>> class Person:

...     name = 'ggondae'

...     age = 36

...     contury = 'Korea'

>> pp = Person()

>> x = hasattr(pp, 'age')

>> print(x)

True


23. id(object)

- 인자로 받은 object의 메모리 주소값을 반환, 실행 시 마다 값은 다름

- 참고 : https://www.w3schools.com/python/ref_func_id.asp

>> x = ('apple', 'banana', 'cherry')

>> y = id(x)

>> print(y)

2220477466432


24. input(prompt)

- 사용자의 입력값을 받아 반환

- 참고 : https://www.w3schools.com/python/ref_func_input.asp

>> x = input('이름을 입력하세요 : ')

>> print(x)

이름을 입력하세요 : ggondae (Commnad창에서 ggondae 입력)

ggondae


25. int(value, base)

- 인자로 받은 값을 int형으로 반환

- 참고 : https://www.w3schools.com/python/ref_func_int.asp

>> int('10')

10

 

>> int(3.8)

3


26. isinstance(object, type)

- 첫번째 인자로 받은 object가 두번째 인자의 타입과 같으면 True, 다르면 False 반환

- 참고 : https://www.w3schools.com/python/ref_func_isinstance.asp

>> x = isinstance('5', int)

>> print(x)

False

 

>> class Person:

...     name = 'ggondae'

...     age = 36

...     contury = 'Korea'

>> pp = Person()

>> x = isinstance(pp, Person)

>> print(x)

True


27. issubclass(object, subclass)

- 첫번째 인자로 받은 object의 서브클래스가 두번째 인자와 같다면 True, 다르면 False 반환

- 참고 : https://www.w3schools.com/python/ref_func_issubclass.asp

>> class Person:

...     name = 'ggondae'

...     age = 36

...     contury = 'Korea'

>> class Student(Person):

...     grade = 3

>> x = issubclass(Student, Person)

>> print(x)

True


28. iter(object, sentinel)

- 첫번째 인자로 받은 반복 가능한 object를 iterator object로 반환, iterator object는 next()를 사용하여 한번에 하나씩 데이터에 접근할 수 있으며 두번째 인자는 옵션으로 반복을 종료할 값

(데이터가 크거나 무한반복의 경우 메모리 효율성을 위해 유용함)

- 참고 : https://www.w3schools.com/python/ref_func_iter.asp

>> x = ['apple', 'banana', 'cherry']

>> y = iter(x)

>> print(f'x : {type(x)}')

>> print(f'y : {type(y)}')

x : <class 'list'>
y : <class 'list_iterator'>

 

>> for item in x:

...     print(f'list : {item}')

list : apple
list : banana
list : cherry

 

>> print(f'list_iterator : {next(y)}')

>> print(f'list_iterator : {next(y)}')

>> print(f'list_iterator : {next(y)}')

list_iterator : apple
list_iterator : banana
list_iterator : cherry


29. len(object)

- 인자로 받은 object의 item수를 반환

- 참고 : https://www.w3schools.com/python/ref_func_len.asp

>> x = ['apple', 'banana', 'cherry']

>> len(x)

3

 

>> y = 'Apple'

>> len(y)

5


30. list(iterable)

- 반복 가능한 object를 인자로 받아 list형으로 반환

- 참고 : https://www.w3schools.com/python/ref_func_list.asp

>> x = ('apple', 'banana', 'cherry')

>> y = list(x)

>> print(f'x : {type(x)}')

>> print(f'y : {type(y)}')

x : <class 'tuple'>
y : <class 'list'>


31. map(function, iterable)

- 첫번째 인자로 실행할 함수를 받고 이 함수에서 필요한 인자는 반복 가능한 인자로 받아 실행 후 결과를 map object로 반환

- 참고 : https://www.w3schools.com/python/ref_func_map.asp

>> def sum(a, b):

...      return a+b

>> x = (1, 2, 3)

>> y = (4, 5, 6)

>> z = map(sum, x, y)

>> print(f'map(z) : {z}')

map(z) : <map object at 0x000001CCD5CF0D60>

 

>> p = list(z)

>> print(f'list(z) : {p}')

list(z) : [5, 7, 9]


32. max(n1, n2, n3 ...) or max(iterable)

- 인자로 받은 object 값 중 가장 큰 값을 반환

- 참고 : https://www.w3schools.com/python/ref_func_max.asp

>> max(1, 2, 3)

3

 

>> x = [1, 2, 3]

>> max(x)

3


33. min(n1, n2, n3 ...) or max(iterable)

- 인자로 받은 object 값 중 가장 작은 값을 반환

- 참고 : https://www.w3schools.com/python/ref_func_min.asp

>> min(1, 2, 3)

1

 

>> x = [1, 2, 3]

>> min(x)

1


34. next(iterable, default)

- 반복 가능한 object (iterator)를 인자로 받아 다음 item 값을 반환, 두번째 인자는 해당 object의 값이 더 이상 없으면 default 값을 반환

- 참고 : https://www.w3schools.com/python/ref_func_next.asp

>> mylist = iter(["apple", "banana", "cherry"])

>> x = next(mylist, "orange")

>> print(x)

>> x = next(mylist, "orange")

>> print(x)

>> x = next(mylist, "orange")

>> print(x)

>> x = next(mylist, "orange")

>> print(x)

apple

banana

cherry

orange


35. object()

- 빈 object를 생성하여 반환

- 참고 : https://www.w3schools.com/python/ref_func_object.asp

>> x = object()

>> print(dir(x))

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']


36. oct(int)

- int형 값을 인자로 받아 8진수 값으로 반환, prefix로 0o 값이 포함

- 참고 : https://www.w3schools.com/python/ref_func_oct.asp

>> oct(10)

0o12


37. open(file, mode, ...)

- 파일 혹은 파일명을 인자로 받아 파일 object를 반환, mode값은 아래 링크 참고

- 참고 : https://www.w3schools.com/python/ref_func_open.asp

>> f = open("file.txt", "r")

>> print(f.read())

(file.txt 내용 출력)

 

>> # binary 타입 파일쓰기

>> with open('파일이름.png', 'wb') as f:

...       f.write(content)

 

>> # CSV 파일 생성 (newline='' -> row와 row 사이 빈 row가 생기지 않게)

>> import csv

>> with open('파일이름.csv', 'w', encoding='utf-8-sig', newline='') as f:

...       w = csv.writer(f)

...       w.writerow('data')


38. ord(character)

- 캐릭터 값을 인자로 받아 유니코드 값 반환

- 참고 : https://www.w3schools.com/python/ref_func_ord.asp

>> ord('h')

104


39. pow(x, y, z)

- 숫자형 인자를 받아 제곱근 및 나머지 값 반환

- 참고 : https://www.w3schools.com/python/ref_func_pow.asp

>> pow(4, 3)       # 4*4*4

64

 

>> pow(4, 3, 5)    # (4*4*4)%5

4


40. print(object, ...)

- object를 인자로 받아 출력, 나머지 옵션은 아래 링크 참고

- 참고 : https://www.w3schools.com/python/ref_func_print.asp

>> print('Hello Python')

Hello Python


41. range(start, stop, step)

- 숫자형 데이터를 첫번째 인자로 받아 순차적인 숫자를 반환, 첫번째 인자 생략 시 시작 기본값은 0, 세번째 인자 생략 시 증가하는 기본값은 1

- 참고 : https://www.w3schools.com/python/ref_func_range.asp

>> x = range(5)

>> for ii in x:

...      print(ii)

0

1

2

3

4

 

>> y = range(2, 10, 2)

>> for jj in y:

...      print(jj)

2

4

6

8


42. reversed(iterable)

- 반복 가능한 object를 인자로 받아 역순서로 바꾼 후 반환

- 참고 : https://www.w3schools.com/python/ref_func_reversed.asp

>> x = [1, 2, 3, 4, 5]

>> for ii in reversed(x):

...      print(ii)

5

4

3

2

1


43. round(number, digits)

- 인자로 받은 숫자를 반올림하여 반환, 2번째 인자가 있으면 인자만큼 소수점 이하 절삭 후 반올림하여 반환

- 참고 : https://www.w3schools.com/python/ref_func_round.asp

>> x = round(3.657)

4

 

>> x = round(3.657, 2)

3.66


44. set(iterable)

- 반복 가능한 object를 인자로 받아 set형으로 반환, set형으로 변경 시 중복된 데이터가 제거되고 object내 데이터가 숫자형이 아닐 경우 순서가 random으로 적용

- 참고 : https://www.w3schools.com/python/ref_func_set.asp

>> x = [1, 2, 3, 4, 4]

>> print(f'list type : {x}')

>> y = set(x)

>> print(f'set type : {y}')

list type : [1, 2, 3, 4, 4]
set type : {1, 2, 3, 4}

 

>> x = ['a', 'b', 'c', 'd', 'd']

>> print(f'list type : {x}')

>> y = set(x)

>> print(f'set type : {y}')

list type : ['a', 'b', 'c', 'd', 'd']
set type : {'b', 'd', 'c', 'a'}


45. setattr(object, attribute, value)

- 첫번째 인자로 받은 object에서 두번째 인자로 받은 attribute를 세번째 인자로 받은 value로 set

- 참고 : https://www.w3schools.com/python/ref_func_setattr.asp

>> class Person:

...     name = 'ggondae'

...     age = 36

...     contury = 'Korea'

>> pp = Person()

>> setattr(pp, 'age', 46)

>> x = getattr(pp, 'age')

>> print(x)

46


46. slice(start, end, step)

- 반복 가능한 object를 숫자형 첫번째 인자 값부터 두번째 인자 값 이전까지 자른 후 반환, 첫번째 인자 생략 시 시작 기본값은 0, 세번째 인자 생략 시 증가하는 기본값은 1

- 참고 : https://www.w3schools.com/python/ref_func_slice.asp

>> x = [1, 2, 3, 4, 5, 6, 7, 8]

>> y = slice(3)

>> print(x[y])

[1, 2, 3]

 

>> x = [1, 2, 3, 4, 5, 6, 7, 8]

>> y = slice(2, 5, 2)

>> print(x[y])

[3, 5]

 

>> x = 'abcdefg'

>> y = slice(3)

>> print(x[y])

abc


47. sorted(iterable, key=key, reverse=reverse)

- 반복 가능한 object를 첫번째 인자로 받아 순서대로 정렬, key 옵션은 해당 값으로 정렬하고 reverse 옵션의 기본값은 False로 True일 경우 역으로 정렬

- 참고 : https://www.w3schools.com/python/ref_func_sorted.asp

>> x = [1, 7, 6, 9, 2, 3, 7]

>> print(f'current x value : {x}')

>> print(f'call sorted() : {sorted(x)}')

>> print(f'x value after sorted() : {x}')

>> x.sort()

>> print(f'x value after sort() : {x}')

current x value : [1, 7, 6, 9, 2, 3, 7]
call sorted() : [1, 2, 3, 6, 7, 7, 9]
x value after sorted() : [1, 7, 6, 9, 2, 3, 7]
x value after sort() : [1, 2, 3, 6, 7, 7, 9]

 

>> y = ['C', 'A', 'E', 'Q', 'L']

>> yy = sorted(y, key=str.upper, reverse=True)

>> print('reverse sorted() : {yy}')

reverse sorted() : ['Q', 'L', 'E', 'C', 'A']

 

>> z = ['banana', 'apple', 'orange', 'cherry']

>> print(sorted(z))

['apple', 'banana', 'cherry', 'orange']

 

>> p = 'kuoamwk'

>> print(sorted(p))

['a', 'k', 'k', 'm', 'o', 'u', 'w']

 

>> q = {3:5,1:6,2:4}

>> # dict를 정렬하면 key값으로 정렬하여 key값만 반환

>> qq = sorted(q)

>> print(f'key sorted() : {qq}')

>> #key값으로 dict의 value를 넣어 value로 정렬

>> qq = sorted(q.items(), key=lambda q:q[1])

>> print(f'value sorted() : {qq}')

key sorted() : [1, 2, 3]
value sorted() : [(2, 4), (3, 5), (1, 6)]


48. str(object, encoding=encoding, errors=errors)

- object를 첫번째 인자로 받아 문자열로 반환

- 참고 : https://www.w3schools.com/python/ref_func_str.asp

>> x = str(3.5)
>> print(type(x))
>> print(x)

<class 'str'>
3.5


49. sum(iterable, start)

- 반복 가능한 숫자형 object 값을 첫번째 인자로 받아 모든 값의 합을 반환, 숫자형의 두번째 인자가 있을 경우 첫번째 인자 object의 처음에 해당값을 추가 후 계산

- 참고 : https://www.w3schools.com/python/ref_func_sum.asp

>> x = (1, 2, 3, 4, 5)>> sum(x)15

 

>> sum(x, 6)21


50. tuple(iterable)

- 반복 가능한 object를 인자로 받아 수정 및 이동이 불가능한 tuple object로 반환참고 : https://www.w3schools.com/python/ref_func_tuple.asp

참고 : https://www.w3schools.com/python/ref_func_tuple.asp

>> x = [1, 7, 6, 9, 2, 3, 7]

>> y = tuple(x)

>> print(type(x))

>> print(type(y))

<class 'list'>
<class 'tuple'>

 

>> print(f'y value : {y}')

(1, 7, 6, 9, 2, 3, 7)

 

>> y[1] = 4

>> print(f'change value : {y}')

Exception has occurred: TypeError
'tuple' object does not support item assignment


51. type(object, bases, dict)

- 첫번째 인자 object의 class 타입을 반환, 

- 참고 : https://www.w3schools.com/python/ref_func_type.asp

>> a = ('apple', 'banana', 'cherry')
>> b = "Hello World"
>> c = 33
>> x = type(a)
>> y = type(b)
>> z = type(c)
>> print(x)
>> print(y)
>> print(z)

<class 'tuple'>
<class 'str'>
<class 'int'>


52. vars(object)

- 인자로 받은 object의 __dict__ 속성 반환, __dict__ 속성은 변경 가능한 속성을 포함한 dict 형태

- 참고 : https://www.w3schools.com/python/ref_func_vars.asp

>> class Person:

...     name = 'ggondae'

...     age = 36

...     contury = 'Korea'

>> x = vars(Person)

>> print(x)

{'__module__': '__main__', 'name': 'ggondae', 'age': 36, 'contury': 'Korea', '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}


53. zip(iterator1, iterator2, iterator3 ...)

- 반복 가능한 object를 인자로 받아 각 object의 데이터를 순차적으로 tuple 형태로 반환

- 참고 : https://www.w3schools.com/python/ref_func_zip.asp

>> a = ("John", "Charles", "Mike")

>> b = ("Jenny", "Christy", "Monica")

>> x = zip(a, b)

>> print(tuple(x))

(('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))

>> c = ["John", "Charles", "Mike"]

>> d = ["Jenny", "Christy", "Monica"]

>> y = zip(c, d)

>> print(list(y))

[('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica')]

반응형