Python解包语法

什么是Python解包语法

简单的例子

刚好数目能对应时

fruits = ["apple", "banana", "cherry"]
fruit_1 , fruit_2 , fruit_3  = fruits
print(fruit_1 , fruit_2 , fruit_3 )

输出:

apple banana cherry

水果数目更多时候

代码:

fruits = ["apple", "banana", "cherry","orange","lemon","mango"]
##水果有 6 个,但是变量只有 5 个的时候就会报错
fruit_1 , fruit_2 , fruit_3 , fruit_4 , other= fruits
print(fruit_1 , fruit_2 , fruit_3 , fruit_4 , other)

输出:


ValueError: too many values to unpack (expected 5)

我们希望吧后面多出来的水果做成一个另外的列表

fruits = ["apple", "banana", "cherry","orange","lemon","mango"]

fruit_1 , fruit_2 , fruit_3 , fruit_4 , *other= fruits
print(fruit_1 , fruit_2 , fruit_3 , fruit_4 , other)

输出:

apple banana cherry orange ['lemon', 'mango']

例子

数字

point = (1,2,3)
x,y,z = point
print(x,y,z)

字符串

a,b,c = "XYZ"
print(a,b,c)

集合

numbers = {1,2,3}
a,b,c=numbers
print(a,b,c)

字典

person = {'name':'Alice','age':30,'city':'New York'}
name , age ,city = person.values()
print(name,age,city)

迭代器

it = iter([1,2,3])
x,y,z=it
print(x,y,z)

生成器

gen=(x * 2 for x in range(3))
a,b,c=gen
print(a,b,c)

矩阵

matrix = [[1,2],[3,4]]
(a,b),(c,d)=matrix
print(a,b,c,d)

参考

https://www.bilibili.com/video/BV1ax4y1D7pj/?spm_id_from=333.337.search-card.all.click&vd_source=160860b3179248eebe67167f9a278e11 Bilibili Python的三大神器之解包(Python五分钟)


© 版权声明
THE END
喜欢就支持一下吧
点赞9赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容