星号 (*
) 可用于 Python 中的不同情况:
*args
, **kwargs
和关键字参数代码:
print(7 * 5)
print(2**4)
结果:
35
16
代码:
# 列表
zeros = [0] * 10
onetwos = [1, 2] * 5
print(zeros)
print(onetwos)
# 元组
zeros = (0,) * 10
onetwos = (1, 2) * 5
print(zeros)
print(onetwos)
# 字符串
A_string = "A" * 10
AB_string = "AB" * 5
print(A_string)
print(AB_string)
结果:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
(1, 2, 1, 2, 1, 2, 1, 2, 1, 2)
AAAAAAAAAA
ABABABABAB
*args
, **kwargs
和关键字参数*args
用于可变长度参数**kwargs
用于可变长度的关键字参数*
后跟更多函数参数来强制仅使用关键字参数代码:
#可变参数
def my_function(*args, **kwargs):
for arg in args:
print(arg)
for key in kwargs:
print(key, kwargs[key])
my_function("Hey", 3, [0, 1, 2], name="Alex", age=8)
#强制关键词参数
def my_function2(name, *, age):
print(name)
print(age)
my_function2("Michael", age=5)
结果:
Hey
3
[0, 1, 2]
name Alex
age 8
Michael
5
*
解压缩为函数参数。**
解包。代码:
def foo(a, b, c):
print(a, b, c)
my_list = [1, 2, 3]
foo(*my_list) # *list传参
my_string = "ABC"
foo(*my_string)
my_dict = {'a': 4, 'b': 5, 'c': 6}
foo(**my_dict) # **dict传参
结果:
1 2 3
A B C
4 5 6
将列表、元组或集合的元素解包为单个和多个剩余元素。
代码:
numbers = (1, 2, 3, 4, 5, 6, 7, 8)
print("*在开始:")
*beginning, last = numbers
print(beginning, last)
print("*在末尾:")
first, *end = numbers
print(first, end)
print("*在中间位置:")
first, *middle, last = numbers
print(first, middle, last)
结果:
*在开始:
[1, 2, 3, 4, 5, 6, 7] 8
*在末尾:
1 [2, 3, 4, 5, 6, 7, 8]
*在中间位置:
1 [2, 3, 4, 5, 6, 7] 8
代码:
# 合并列表
my_tuple = (1, 2, 3)
my_set = {4, 5, 6}
my_list = [*my_tuple, *my_set]
print(my_list)
# 合并字典
dict_a = {"one": 1, "two": 2}
dict_b = {"three": 3, "four": 4}
dict_c = {**dict_a, **dict_b}
print(dict_c)
结果:
[1, 2, 3, 4, 5, 6]
{'one': 1, 'two': 2, 'three': 3, 'four': 4}