1. 乘法运算符
#
- 乘法
print(5*3)
» 15
- 幂乘
print(2**3)
» 8
2. 字符串/列表 重复
#
>>> print('a'*10)
aaaaaaaaaa
>>> print([1,2,3]*3)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
3.打包
#
def print_values(*args):
for arg in args:
print(arg)
print_values(1,2,3,4)
输出>>
1
2
3
4
def eg(**kwargs):
for k,v in kwargs.items():
print(f'{k}={v}')
>>> eg(a=1,b=2)
a=1
b=2
a, *b = [1, 2, 3, 4]
print(a) # 输出: 1
print(b) # 输出: [2, 3, 4]
4.解包
#
def func(a, b, c):
print(a, b, c)
args = (1, 2, 3)
func(*args) # 输出: 1 2 3
- ‘**’ 解包字典中的键值对,作为函数的关键字参数。
def func(a, b, c):
print(a, b, c)
kwargs = {'a': 1, 'b': 2, 'c': 3}
func(**kwargs) # 输出: 1 2 3
list1=[1,2,3]
tuple1=(4,5,6)
merged=[*list1,*tuple1]
#merged=[1,2,3,4,5,6] 这里解包之后到[]里了
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2}
print(merged) # 输出: {'a': 1, 'b': 3, 'c': 4}
总结
#
- 函数定义时带星号的形参负责打包,而函数调用时传入函数的带星号的实参负责解包
参考
#
【Python摸鱼读物】*:别只把它当乘号,还能打包和解包