Python - * 활용

lsjoon·2024년 1월 15일
0

python

목록 보기
13/16

가변인자

  • *args
    위치 인자 (potitional Arguments)
  • **kwargs
    키워드 인자 (keyword Arguments)
from math import pow
to_power = [3,4]

print(pow(to_power[0],to_power[1]))		## result = 81
print(pow(*to_power))					## result = 81
def args_function(*args):
    print(args)

def kwargs_function(**kwargs):
    print(kwargs)

args_function('a', 'b') 				## result =  ('a', 'b')
kwargs_function(a = 100, b = 200) 		## result = {'a':100, 'b':200}

Unpacking

# list unpacking
test = [1, 2, 3, 4]
print(*test) # 1 2 3 4

# tuple unpacking
test = (5, 6, 7, 8)
print(*test) # 5 6 7 8

* 가 붙는 위치에 따라 변수에 할당되는 값들의 형태가 변화

test = [1, 2, 3, 4, 5]

*a, b = test
print(a, b) # [1, 2, 3, 4], 5

a, *b, c = test
print(a, b, c) # 1, [2, 3, 4], 5

활용 예시

nums = [i for i in range(10)]

# output: "0 1 2 3 4 5 6 7 8 9"
print(' '.join(map(str,nums)))
print(*nums)
# example input: "5 1 3 5 7 9"
# output = 25				>> 맨 처음 5는 n에 담김, 나머지는 nums 에 담긴 후 합계 출력
n,*nums = map(int, input().split())
print(sum(nums))
# input:
# 1 2
# 3 4
# 5 6
# 7 8

# out put :
# 3,4
# 5,6
# 7,8			>> 첫 1,2 는 n, m에 담김, 나머지는 a에 담긴 뒤 출력
[n,m],*a=[map(int,i.split())for i in open(0)]
for x,y in a:print(x,y)

0개의 댓글