본문 바로가기
Python/Python

변수 _, *x (map을 list로 만드는 방법에 대해)

by Sondho 2020. 4. 29.

_

  • 값을 무시함
  • 파이썬 인터프리터에선 마지막으로 실행된 결과값이 저장됨 (인터프리터에 사용하는 경우)
# _ 예제
x, _, y = 1, 2, 3
print(f"x : {x}")
print(f"y : {y}")


# 실행결과
x : 1
y : 3

*_

  • 여러개의 값을 무시하고 받음
# *_ 예제
x, *_, y = 1, 2, 3, 4, 5
print(f"x : {x}")
print(f"y : {y}")


# 실행결과
x : 1
y : 5

_, *x

  • 여러개의 값을 한번에 받아옴. list로 반환
# 응용
import sys

_, *x = map(int, sys.stdin.readline().split())
print(type(x))
print(x)
print(f"{min(x)}\n{max(x)}")


# 실행결과
5 30 10 24 87
<class 'list'>
[30, 10, 24, 87]
min(x) : 10
max(x) : 87
# _ 가 없으면 에러 발생
import sys

*x = map(int, sys.stdin.readline().split())
print(type(x))
print(x)
print(f"{min(x)}\n{max(x)}")


# 실행결과
File "g:\test.py", line 3
    *x = map(int, sys.stdin.readline().split())
SyntaxError: starred assignment target must be in a list or tuple
# map을 list로 구성하는 다른 방법
import sys

n = int(input())
x = list(map(int, sys.stdin.readline().split()))
print(f"min(x) : {min(x)}")
print(f"max(x) : {max(x)}")


# 실행결과
5 30 10 24 87
<class 'list'>
[30, 10, 24, 87]
min(x) : 10
max(x) : 87

댓글