1. 곱셈 및 거듭제곱

>>> 3 * 5
15

>>> 4 ** 3
64

2. 리스트형 컨테이너 타입 데이터 반복확장

# 숫자형 데이터 뿐만 아니라 리스트형 컨테이너 타입에서 데이터를 반복적으로 확장할 수 있음.

# 길이 100의 제로값 리스트 초기화
zeros_list = [0] * 100

# 길이 100의 제로값 튜플 선언
zeros_tuple = (0,) * 100

# 리스트 3배 확장 후 연산
vector_list = [[1, 2, 3]]
for i, vector in enumerate(vector_list * 3):
    print("{0} scalar product of vector: {1}".format((i + 1), [(i + 1) * e for e in vector]))
# 1 scalar product of vector: [1, 2, 3]
# 2 scalar product of vector: [2, 4, 6]
# 3 scalar product of vector: [3, 6, 9]

3. 가변인자(Variadic Parameters)

a. positional arguments(*args): 위치 가변 인자, 임의의 개수의 인자를 받는 함수

def f(x, *args): 
	...

f(1, 2, 3, 4, 5)

def f(x, *args):
	# x -> 1
	# args -> (2, 3, 4, 5)

b. keyword arguments(**kwargs): 키워드 가변 인자, 임의의 개수의 키워드 인자를 받는 함수

def f(x, y, **kwargs): 
	...

f(2, 3, flag=True, mode='fast', header='debug')

def f(x, y, **kwargs): 
	# x -> 2 
	# y -> 3 
	# kwargs -> { 'flag': True, 'mode': 'fast', 'header': 'debug' }

c. 두 가지를 혼합: 함수는 임의의 개수의 가변 인자와 키워드 없는 인자들을 받을 수 있다.

def f(*args, **kwargs): 
	...

f(2, 3, flag=True, mode='fast', header='debug')

def f(*args, **kwargs): 
	# args = (2, 3) 
	# kwargs -> { 'flag': True, 'mode': 'fast', 'header': 'debug' } 
	...

d. 튜플과 딕셔너리를 전달하기

  • 튜플을 전달할땐 *, 딕셔너리를 전달할 땐 **를 사용한다.
numbers = (2,3,4) 
f(1, *numbers) # f(1,2,3,4)와 같음

options = { 
		   'color' : 'red', 
		   'delimiter' : ',', 
		   'width' : 400 
} 
f(data, **options) 
# f(data, color='red', delimiter=',', width=400)와 같음

4. 컨테이너 타입의 데이터 Unpacking

*를사용하여 가변적으로 언패킹할 수 있다.

numbers = [1, 2, 3, 4, 5, 6]

# unpacking의 좌변은 리스트 또는 튜플의 형태를 가져야하므로 단일 unpacking의 경우 *a가 아닌 *a,를 사용
*a, = numbers
# a = [1, 2, 3, 4, 5, 6]

*a, b = numbers
# a = [1, 2, 3, 4, 5]
# b = 6

a, *b, = numbers
# a = 1
# b = [2, 3, 4, 5, 6]

a, *b, c = numbers
# a = 1
# b = [2, 3, 4, 5]
# c = 6

참고문헌)

https://mingrammer.com/understanding-the-asterisk-of-python/

https://wikidocs.net/84426

profile
반갑습니다

0개의 댓글

Powered by GraphCDN, the GraphQL CDN