Python数据的封装与解构

Python等式右侧出现逗号分隔的多值的时候,就会将这几个值封装到元组中。这种操作称为封装packing。

封装

t1=1,2
type(t1)
Out[3]: tuple
t1
Out[4]: (1, 2)

封装和解构基本概念Python等式右侧出现逗号分隔的多值的时候,就会将这几个值封装到元组中。这种操作称为封装packing。Python中等式右侧是一个容器类型,左侧是逗号分隔的多个标识符,将右侧容器中数据的一个个和左侧标识符一一对应。这种操作称为解构unpacking

解构

t1=1,2
x,y=t1
x
Out[9]: 1
y
Out[10]: 2

封装和解构,交换

x = 10
y = 11
x,y = y,x

简单解构

a,b = (1,2)
a
Out[13]: 1
b
Out[14]: 2
    
a,b = [1,2]
a
Out[16]: 1
b
Out[17]: 2

a,b = [10,20]
a
Out[19]: 10
b
Out[20]: 20
    
a,b = {10,20} # 非线性结构
a
Out[22]: 20
b
Out[23]: 10
    
a,b = {'a':10,'b':20} # 非线性结构也可以解构
a
Out[25]: 'a'
b
Out[26]: 'b'

剩余变量解构

a, *rest, b = [1, 2, 3, 4, 5]
print(a, b)
1 5
print(type(rest), rest)
<class 'list'> [2, 3, 4]

剩余变量是不允许单独使用的

*rest = [1, 2, 3, 4, 5]

Traceback (most recent call last):
  File "C:\Python\Python368\lib\site-packages\IPython\core\interactiveshell.py", line 3233, in run_ast_nodes
    async_wrapper_code = compiler(mod, cell_name, 'exec')
  File "C:\Python\Python368\lib\codeop.py", line 133, in __call__
    codeob = compile(source, filename, symbol, self.flags, 1)
  File "<ipython-input-31-c3e7fa75df11>", line 4
SyntaxError: starred assignment target must be in a list or tuple

也不可以多用

a, *r1, *r2, b = [1, 2, 3, 4, 5]

Traceback (most recent call last):
  File "C:\Python\Python368\lib\site-packages\IPython\core\interactiveshell.py", line 3233, in run_ast_nodes
    async_wrapper_code = compiler(mod, cell_name, 'exec')
  File "C:\Python\Python368\lib\codeop.py", line 133, in __call__
    codeob = compile(source, filename, symbol, self.flags, 1)
  File "<ipython-input-33-ebb94b30b18a>", line 4
SyntaxError: two starred expressions in assignment

_是合法的标识符,这里它没有什么可读性,它在这里的作用就是表示不关心这个变量的值,我不想要。有人把它称作丢弃变量

_, *b, _ = [1, 2, 3]
print(_)
3
print(b)
[2]
print(_)
3
posted @ 2022-11-21 10:00  厚礼蝎  阅读(116)  评论(0编辑  收藏  举报