Python解压序列

一.普遍情况:

x,y,z = 1,2,3
 
print("x:",x)
# x:1
print("y:",y)
# y:2
print("z:",z)
# z:3

二.针对元祖:

name = ("qiaobushi","wanglihong","leibushi")
x,y,z = name
 
print(name)
print("x:",x)
print("y:",y)
print("z:",z)
'''
运行结果
('qiaobushi', 'wanglihong', 'leibushi')
x: qiaobushi
y: wanglihong
z: leibushi
'''

三.针对字符串:

a,b,c='hel'
print(a)
print(b)
print(c)
# h
# e
# l  

四.针对列表:

# 定义绩效列表
list = [10,3,5,6,22,8,12,44] 
 
# 需求:只要开头和结尾的数值
# *代表中间所有的  _代表一个变量,因为我们不想要了,所以使用_,*后面必须跟一个变量
a,*_,c=list 
print(a)
print(c)
# 10
# 44
 
a,*d,c=list
print(a)
# 10
print(d)
# [3, 5, 6, 22, 8, 12]
print(c)
# 44  

五.针对dict序列解包获:得key和value

#学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
#法1
dict1 = {"one":1,"two":2,"three":3}
x,y,z = dict1
print("key-x:",x)
print("key-y:",y)
print("key-z:",z)
print("value-x:",dict1[x])
print("value-y:",dict1[y])
print("value-z:",dict1[z])
 
#法2
dict1 = {"one":1}
x,y = dict1.popitem()
print("key:",x,"value:",y)
 
'''
#运行结果
key-x: one
key-y: two
key-z: three
value-x: 1
value-y: 2
value-z: 3
key: one value: 1
'''  

六.对变量的值进行交换:

f1=1
f2=2
 
# 需求把f1和f2的值进行交换
#
f1,f2=f2,f1
print(f1,f2)
# 2 1
posted @ 2024-04-02 15:54  python学习者0  阅读(6)  评论(0编辑  收藏  举报