python学习

python \*和**用法、序列解包

2019-08-12  本文已影响0人  caizhanjin
1.算数运算

* 代表乘法
** 代表乘方

2.函数形参

主要用于函数定义,区别:

def fun(name, *args, **kwargs):
  print(name)
  print(args)
  print(kwargs)
 
fun(1, 2, 3, 4, 5, a="1", b="2", c="3")

1
(2, 3, 4, 5)
{a="1", b="2", c="3"}
3.函数实参

如果函数的形参是定长参数,也可以使用 *args 和 **kwargs 调用函数,类似对元组和字典进行解引用。

def fun(data1, data2, data3):
  print("data1: ", data1)
  print("data2: ", data2)
  print("data3: ", data3)
  
args = ("one", 2, 3)
fun(*args)

data1:  one
data2:  2
data3:  3

kwargs = {"data3": "one", "data2": 2, "data1": 3}
fun(**kwargs)

data1:  3
data2:  2
data3:  one
4.序列解包
a, b, c = 1, 2, 3
# a = 1
# b = 2
# c = 3
a, b, *c = 0, 1, 2, 3
# a = 0
# b = 1
# c = (2, 3)

获取中间部分:

a, *b, c = 0, 1, 2, 3
# a = 0
# b = (1, 2)
# c = 3

如果左值比右值要多,那么带 * 的变量默认为空:

a, *b, c = a, b, *c = 0, 1
# a = 0
# b = 1
# c = ()

嵌套解包:

(a, b), (c, d) = (1, 2), (3, 4)
# a = 1
# b = 2
# c = 3
# d = 4

出处:
https://blog.csdn.net/yilovexing/article/details/80577510
https://blog.csdn.net/yilovexing/article/details/80576788

上一篇 下一篇

猜你喜欢

热点阅读