Python入门之Python函数
2020-06-28 14:44:40 来源:易采站长站 作者:易采站长站整理
'earth.mars.venus'
>>> concat("earth", "mars", "venus", ".")
此外,如果我们有一个列表
["earth", "mars", "venus"] ,或者元组
("earth", "mars", "venus"),想传入 concat()函数怎么办呢?如果我们直接把列表或者元组传进去都会报错,正确的做法是解包参数列表,即传入
*List 和
*tuple 的形式,
* 可以理解为去掉
[] 或者
(),这非常常用且实用。示例如下:
>>> list_a = ["earth", "mars", "venus"]>>> concat(list_a)
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in concat
TypeError: sequence item 0: expected str instance, list found
>>> concat(*list_a)
'earth/mars/venus'
>>> t = ("earth", "mars", "venus")
>>> concat(t)
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in concat
TypeError: sequence item 0: expected str instance, tuple found
>>> concat(*t)
'earth/mars/venus'
**kwargs 可变关键字参数示例:
def kwargs_fun(**kwargs):
for key in kwargs:
print(f'{key}:{kwargs[key]}')kwargs_fun(a=1, b=2, c=3)
输出结果:
a:1
b:2
c:3
*args 和
**kwargs 组合使用示例:
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
输出结果:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
此外,字典中也可以用解包,符号是
**dict,相当于去掉
{},测试如下:
>>> def parrot(voltage, state='a stiff', action='voom'):













闽公网安备 35020302000061号