python assignment method

'''
 spam='spam' Basic form
 spam, ham='spam','ham' Tuple assignment (positional)
 [spam, ham]=['spam','ham'] List assignment (positional) )
 a,b,c,d='spam' sequence assignment, generality
 a,*b='spam' extended sequence unpacking
 spam=ham='spam' multi-objective assignment
 spam+=42 enhanced assignment (equivalent to In spam=spam+42)
 '''
 #Multi-objective assignment operation
 a=b=c= 'spam'
 print (a,b,c)     #spam spam spam
 print ( id (a), id (b), id ( c))     #The address is consistent

 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)  




#spam
 #a,b,c=string #ValueError: too many values ​​to unpack (expected 3) The length of the left and right sides must be the same
 a,b,c=string[ 0 ],string[ 1 ],string[ 2 :]
 print (a,b,c)     #sp am
 a,b,c= list (string[: 2 ])+[string[ 2 :]]
 print (a,b,c)     #sp 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 []
 #Extended sequence unpacking---when the left and right lengths are not equal, no error will be reported
 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:
    forehead,*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 [] Assign an empty list a,b,*c,d,e=seq
 print (a,b,c when there is nothing left to match the asterisked name
 ,d,e)     #1 2 [] 3 4 When there is no remaining content to match the name with an asterisk, assign an empty list
 #*a=seq #Error SyntaxError: starred assignment target must be in a list or tuple
 *a,=seq
 print (a)     #['1', '2', '3', '4']
 #Enhanced assignment statement
 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]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326000342&siteId=291194637