WeSTUDY | 3주차 내장함수

juri·2021년 6월 15일
0

We STUDY

목록 보기
10/16
post-thumbnail

🥨 파이썬 자체에 내장돼있는 함수의 종류는 아주 다양하다. 그 중에서 낯선 것들을 골라서 직접 코드를 써보고 수정해보는 시간을 가져보았다.

Index

(1) eval()
(2) open()
(3) filter()
(4) format()
(5) set()
(6) zip()
(번외) help()

참고 : w3schools


(1) eval()

The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.
🍟 eval()은 문자열로 된 argument를 수식으로 바꿔 계산을 가능하게 해주는 함수다.

Example

x = '3+2'
eval(x)
//5
  • input()처럼 입력받은 값을 문자열로 저장하는 함수를 다룰 때 유용하다.

(2) open()

The open() function opens a file, and returns it as a file object.
🍟 파일을 파이썬 내에 여는 함수로 열린 파일을 객체로 반환한다.

Example

f = open('script.txt', 'r') #읽기모드
f.read()
f.close()
  • r읽기모드, w쓰기모드 등 여러가지 모드가 있다.
  • 파일을 열어서 읽고 난 후 파일을 닫아줘야 한다.
  • 열고자 하는 파일이 있는 경로로 이동해야 한다.

(3) filter()

The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.
🍟 시퀀스 자료형(iterable)을 지정한 함수로 필터링해 조건을 만족하는 값을 반환하는 함수다.

기본형

filter(function, iterable)

Example

y = [0, 1, 2, '', None, False, 'Flower'] 
list(filter(None, y))
//[1, 2, 'Flower']
  • 값을 반환할 때 list형태로 unpack 해줘야 한다.
  • 함수를 None으로 지정하면, 0, '', None, False 값을 제거한다.
  • 주로 lambda함수를 사용한다.

(4) format()

The format() function formats a specified value into a specified format.
🍟 지정한 format으로 value를 변경한다.

기본형

format(value, format)

Example

x = format(0.5, '%')
print(x)
//50.000000%
x = 3.4556
print(format(x, '.2f')
//3.46
  • 문자열로 반환한다.

🍩번외) 소수점 자릿수 지정하기

x = 3.141592
y = 3.103

format()

format(x, '.3f')
//'3.142'
format(y, '.2f')
//'3.10'

round()

round(x, 3)
//3.142
round(y, 2)
//3.1
  • 값을 반올림한다.
  • round()는 끝자리가 0이면 출력하지 않는다.

(5) set()

The set() function creates a set object.
🍟 시퀀스 자료형을 set자료형으로 만든다.

Example

y = [1, 1, 1, 2, 3, 3]
print(set(y))
//{1, 2, 3}
  • set은 중복된 원소를 제거한다.

(6) zip()

The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
🍟 두 개의 시퀀스 자료를 순서대로 짝지어 하나의 자료형으로 만들어준다.

Example

a = ('jisoo', 'minsu', 'minhyuk')
b = ('apple', 'banana', 'grape')
c = zip(a,b)
dict(c)

출력값

{'jisoo': 'apple', 'minsu': 'banana', 'minhyuk': 'grape'}
  • 출력가능한 값으로 unpack해야한다.

후기

이 많은 내장함수의 기능을 다 외울 순 없으니 전체적으로 쓱 훑어보고 나중에 필요할 때 검색해서 필요한 기능만 쏙쏙 빼서 쓰면 될 것 같당 😁

profile
Make my day !

0개의 댓글