1、直接赋值
>>> y = 1
>>> x = (1,'one')
>>> z = ['age',18]
>>> o = 'strong'
>>> y
1
>>> x
(1, 'one')
>>> z
['age', 18]
>>> o
'strong'
>>> d = {'name':'Hiden'}
>>> d
{'name': 'Hiden'}
2、解包赋值,常用于函数或者方法返回元组(或其他序列或可迭代对象)时
>>> x,y,z = (1,2,3)
>>> x
1
>>> y
2
>>> z
3
>>> dic = {'age':18,'addr':'BeiJing'}
>>> k,v = dic.popitem()
>>> k
'addr'
>>> v
'BeiJing'
###带*号的变量解包
>>> a,b,*res = (1,2,3,4)
>>> a
1
>>> b
2
>>> res ###list格式
[3, 4]
####注意:解包的序列元素数量要与=左边的变量数量完全一致,否则会报错
>>> x,y,z = 1,2
Traceback (most recent call last):
File "", line 1, in
x,y,z = 1,2
ValueError: not enough values to unpack (expected 3, got 2)
>>> x,y = 1,2,3
Traceback (most recent call last):
File "", line 1, in
x,y = 1,2,3
ValueError: too many values to unpack (expected 2)
3、链式赋值
>>> x = y =somefunction()
但是不一定等同于
x=somefunction()
y=somefunction()
4、增量赋值
x+=1(-、%、/等标准运算符也适用)
对于其他数据类型也适用,只要二元运算符适用于这些数据结构即可:
>>> fnord = 'foo'
>>> fnord +='bar'
>>> fnord*=2
>>> fnord
'foobarfoobar'