Python的赋值语句是将对象赋值给变量。 基本格式是在等号左侧写赋值语句的目标,要赋值的对象位于等号右侧。 等号左侧是对象或对象组件,等号右侧是可以通过计算获得对象的任何表达式。赋值语句总是创建对对象的引用,而不是复制对象。 Python3的赋值语句有赋值语句的形式。
1:基础形式
s='ixusy88 's
' ixusy88 '
2:元组赋值
(S1,s2 )=(123 ),abc ) )。s1、s2
(' 123 ',' abc ' )
#括号(也可以不需要() ) )
s1,s2='111 ',' cccc '
s1、s2
((111 )、(cccc ) ) )
#左和右要素必须一致。 如果不匹配,则报告以下错误:
s1,s2='111 ',' 222 ',' 333 '
跟踪后退(mostrecentcalllast ) :
File 'pyshell#20 ',line 1,in module
s1,s2='111 ',' 222 ',' 333 '
value error : toomanyvaluestounpack (expected2)。
3:列表赋值
[a,b]=['123 ',' abc']A,B
(' 123 ',' abc ' )
#
a,b=['123 ',' abc']
A,B
(' 123 ',' abc ' )
可以在等号右侧指定元组
[a,b]='123 ','
A,B
(' 123 ',' abc ' )
等号两侧的元素必须匹配
[a,b,c]=['123 ',' abc']
跟踪后退(mostrecentcalllast ) :
File 'pyshell#56 ',line 1,in module
[a,b,c]=['123 ',' abc']
value error : notenoughvaluestounpack (expected 3,got 2)。
[a,b]=['123 ',' abc ',' 444']
跟踪后退(mostrecentcalllast ) :
file'py外壳#57 ',line 1,in module
[a,b]=['123 ',' abc ',' 444']
value error : toomanyvaluestounpack (expected2)。
4:序列赋值
a,b,c,d='1234 'a、b、c、d
(1)、2 )、3 )、4 ) )
等号两侧的元素必须一致
a,b,c,d='123 '
跟踪后退(mostrecentcalllast ) :
File 'pyshell#91 ',line 1,in module
a,b,c,d='123 '
value error : notenoughvaluestounpack (扩展4,got 3) )。
a,b,c='1234 '
跟踪后退(mostrecentcalllast ) :
File 'pyshell#92 ',line 1,in module
a,b,c='1234 '
value error : toomanyvaluestounpack (expected3)。
5:序列解包
#带星号的名称将分配一个列表,其中包含序列中未分配给其馀名称的所有项目的集合a,*b='ixusy88 '
A,B
((I )、(x )、u )、s )、y )、8 )、8 ) )
a,*b,c='ixusy88 '
A、B、C
((I )、(x )、u )、s )、y )、8 )、8 ) )
a,* b=[ 1,2,3,4 ]
A,B
(1,[ 2,3,4 ] ) ) )。
a,*b,c=[ 1,2,3,4,5 ]
A、B、C
(1,[ 2,3,4 ],5 )。
a,*b,c=范围(5) ) )
A、B、C
(0,[ 1,2,3 ],4 )。
a,*b,c=[ 1,2,3 ]
A、B、C
(1,[2],3 ) )。
6:多目标赋值
#个变量指向同一对象a=b=c='ixusy88 '
A,id(a ) )。
(ixusy88 )、2197246939464 ) ) )。
b,id(b ) )。
(ixusy88 )、2197246939464 ) ) )。
C,id(c ) )。
(ixusy88 )、2197246939464 ) ) )。
7:增量赋值
增量赋值语句如下:x =y x=y x -=y x |=y
x *=y x ^=y x /=y x=y
x %=y x=y x **=y x //=y
# '='将在列表中的原始位置进行修改。
a=[ 1,2,3 ]
b=[ 3,4,5 ]
print('1----',id ) a ),a ) )
打印('2----',id (b ),b ) ) ) ) ) ) )。
a=b
打印(3----)、id (a )、a ) )
打印(' * ' * 10 ) ) ) ) ) )。
# ' '是拼接,产生新的对象:
x=[ 10,20,30 ]
y=[ 30,40,50 ]
打印('4----',id ) x ),x ) ) ) ) ) )。
打印('5----',id ) y ),y ) ) ) ) ) )。
x=x y
打印('6----',id ) x ),x ) ) ) ) ) )。