python 赋值方式

'''
spam='spam'   基本形式
spam,ham='spam','ham'   元组赋值运算(位置性)
[spam,ham]=['spam','ham']  列表赋值运算(位置性)
a,b,c,d='spam'   序列赋值运算,通用性
a,*b='spam'   扩展的序列解包
spam=ham='spam'   多目标赋值运算
spam+=42   增强赋值运算(相当于spam=spam+42)
'''
#多目标赋值运算
a=b=c='spam'
print(a,b,c)    #spam spam spam
print(id(a),id(b),id(c))    #地址一致

a=b=0
b=b+1
print(a,b)  #0 1

a=b=[]
a.append(1)
print(a,b)  #[1] [1]

#序列赋值
a=1
b=2
A,B=a,b
print(A,B)   #1 2

a,b=a,b
print(a,b)  #1 2

[a,b,c]=[1,2,3]
print(a,b,c)    #1 2 3
print([a,b,c])  #[1, 2, 3]
print((a,c))    #(1, 3)

(a,b,c)="spa"
print(a,b,c)    #s p a

string='spam'
a,b,c,d=string
print(a,b,c,d)  #s p a m

#a,b,c=string     #ValueError: too many values to unpack (expected 3) 左右两边的长度必须要一样

a,b,c=string[0],string[1],string[2:]
print(a,b,c)    #s p am

a,b,c=list(string[:2])+[string[2:]]
print(a,b,c)    #s p am

a,b=string[:2]
c=string[2:]
print(a,b,c)    #s p am

(a,b),c=string[:2],string[2:]
print(a,b,c)    #s p am

red,green,blue=range(3)
print(red,green,blue)   #0 1 2

l=[1,2,3,4]
while l:
    front, l=l[0],l[1:]
    print(front,l)

#1 [2, 3, 4]
#2 [3, 4]
#3 [4]
#4 []

#拓展序列解包---当左边和右边长度不等时,不会报错
seq=[1,2,3,4]
a,*b=seq
print(a)    #1
print(b)    #[2,3,4]

seq=[1,2,3,4]
*a,b=seq
print(a)    #[1, 2, 3]
print(b)    #4

seq=[1,2,3,4]
a,*b,c=seq
print(a)    #1
print(b)    #[2,3]
print(c)    #4

seq=[1,2,3,4]
#*a,*b=seq    #报错SyntaxError: two starred expressions in assignment

seq=(1,2,3,4)
a,*b=seq
print(a)    #1
print(b)    #[2,3,4]

seq='1234'
a,*b=seq
print(a)    #1
print(b)    #['2','3','4']

l=[1,2,3,4]
while l:
    front,*l=l
    print(front, l)
#1 [2, 3, 4]
#2 [3, 4]
#3 [4]
#4 []

a,b,c,d,*e=seq
print(a,b,c,d,e)    #1 2 3 4 []  当没有剩下的内容可以匹配带星号的名称,则赋值一个空列表

a,b,*c,d,e=seq
print(a,b,c,d,e)    #1 2 [] 3 4  当没有剩下的内容可以匹配带星号的名称,则赋值一个空列表

#*a=seq    #报错SyntaxError: starred assignment target must be in a list or tuple

*a,=seq
print(a)    #['1', '2', '3', '4']

#增强赋值语句
x=1
x+=1
print(x)    #2

s='spam'
s+=s
print(s)    #spamspam

l=[1,2]
l+=[3,4]
print(l)    #[1, 2, 3, 4]

你可能感兴趣的:(python)