1. 封包(packing)与解包(unpacking)
1.1. 概念
封包:把多个值赋值给一个变量时,Python会自动的把多个值封装成元组,称为封包。
解包:把一个可迭代对象(列表、元组、字符串、字典等)赋值给多个变量时,python会自动把对象中的各个元素依次赋值给每个变量,这称为解包
主要两个方面应用:1. 赋值 2.函数传参
# 赋值,封包
a = 1,2,3
print(type(a), a)
<class 'tuple'> (1, 2, 3)
# 赋值,解包
a1,a2,a3 = a
print(type(a1), a1)
print(type(a2), a2)
print(type(a3), a3)
<class 'int'> 1
<class 'int'> 2
<class 'int'> 3
# 函数传参
def func():
return 1,2,3
a = func()
print(type(a), a)
<class 'tuple'> (1, 2, 3)
封包/解包的过程都是自动执行的,当判断赋值两边变量-元素个数不等时,就会触发,但自动执行一般是用于1对多或者多对1的情况
1.2 利用*进行解包
* 可以对可迭代对象进行解包操作。
1.2.1 用于赋值
a,c, *b = 1,2,3,4,5
print(type(c), c)
print(type(b), b)
<class 'int'> 2
<class 'list'> [3, 4, 5]
(1, *[2,3]) == (1,2,3)
True
*b, = 1,2,3
print(b)
分数统计小例子:
scores = [98,94,91,88,86,82,77,76,71,65]
first, *middle, last = scores
print('第一名的成绩:',first) # 98
print('最后一名的成绩',last) # 65
print('中间成绩:', middle) # [94,91,88,86,82,77,76,71]
第一名的成绩: 98
最后一名的成绩 65
中间成绩: [94, 91, 88, 86, 82, 77, 76, 71]
如果不使用解包操作*,上面分数统计的例子就得使用切片操作这样写:
scores = [98,94,91,88,86,82,77,76,71,65]
first, middle, last = scores[0], scores[1:-1], scores[-1]
把多个list合并为一个整体:
a = [1,2,3,4]
b = [5,6,7]
c = [8,9]
d = [*a,*b,*c]
print(d)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
numpy的例子:
import numpy as np
a = np.array([[1,2,3],[2,3,4]])
b = np.array([[3,4,5],[4,5,6]])
c = np.array([*a, *b]) # np.concatenate([a,b], axis=0)
print(c)
[[1 2 3]
[2 3 4]
[3 4 5]
[4 5 6]]
np.sum([[1,2,3],[4,5,6]], axis=0)
array([5, 7, 9])
1.2.2 函数传参
求任意个number的均值:
def mean(*args):
sum = 0
for i in args:
sum = sum + i
return sum/len(args)
# 调用方式一:
mean(1,2,3,4)
2.5
# 调用方式二:
a = [1,2,3,4]
mean(*a)
for fun:
a,b,*c= *(1,2),3,4,5
print(a)
print(c)
1
[3, 4, 5]
a,b,*c= (1,2),3,4,5
print(a)
print(c)
(1, 2)
[4, 5]
record = ('ACME', 50, 123.45, (12, 18, 2012))
name, *_, (*_, year) = record # _ 表示匿名变量
print(name)
print(year)
ACME
2012
1.3 利用**解包
*主要用于对字典解包。当然也可以用于对字典解包,区别是把字典当迭代对象看,*当作键值对看。
1.3.1 字典的基础知识补充
# keys(), values(), items()
dic = {'a':1, 'b':2, 'c':3}
a,b,c = dic.items()
print(a,b,c)
('a', (1, 1)) ('b', 2) ('c', 3)
1.3.2 *对字典解包
dic = {'a':1, 'b':2, 'c':3}
a, *b = dic.items()
print(b)
1.3.2 **对字典解包
合并两个字典:
dic1 = {'a': 1, 'b':2}
dic2 = {'c': 3, 'd':4}
dic3 = {**dic1, **dic2}
print(dic3)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
错误范例:
dic = {'a':1, 'b':2, 'c':3}
a, **b = dic
File "<ipython-input-48-ed9473e346b8>", line 2
a, **b = dic
^
SyntaxError: invalid syntax
{'a':1, 'b':2, 'c':3} == {'b':2, 'c':3, 'a':1}
True
2. 函数参数
位置(positional)参数, 关键字(keyword)参数,普通参数,默认参数,变长参数,限定位置(positional-only)参数,限定关键字(keyword-only)参数
def sum(a,/,*,lr):
print(lr)
return a+lr
sum(1,lr=0.001)
0.001
1.001
def func(**kargs):
print(len(kargs))
print(kargs)
a = {'a':1, 'b':2}
func(**a)
2
{'a': 1, 'b': 2}
def test(a, b, *args, **kwargs):
print(a)
print(b)
print(type(args), len(args), args)
print(type(kwargs), len(kwargs), kwargs)
# test(1,2,3,4,5,x=8,y=9)
# test(1,2,3,4,5, {'6':6,'7':7},x=8,y=9)
test(1,2,3,4,5, **{'6':6,'7':7},x=8,y=9)
1
2
<class 'tuple'> 3 (3, 4, 5)
<class 'dict'> 4 {'6': 6, '7': 7, 'x': 8, 'y': 9}
网友评论