赋值语句

  • 序列解包
序列解包或者递归解包--将多个值的序列解开,而后放到变量的序列
x,y,z = 1,2,3  #多个同时进行赋值
print x,y,z

x,y = y,x      #直接交换,不须要中间变量
print x,y

values = 1,2,3
print type(values)  #注意 type() 函数显示values是元祖
print values
x1,y1,z1 = values
print x1

#输出
1 2 3
2 1
<type 'tuple'>
(1, 2, 3)
1

scoundrel = {'name':'a','sex':'female','age':'ten'} 

#获取键-值
s =scoundrel.items()  #字典中全部的项,以列表的形式返回
print s               #输出:[('age', 'ten'), ('name', 'a'), ('sex', 'female')]
a1,n1,s1 = s          #定义变量将每一个每项取出来
print a1              #输出:('age', 'ten')
print type(a1)        #输出:<type 'tuple'>, a1是元祖,那么继续赋值,将 a1 中的值取出
a2,t = a1             
print a2,t            #输出:age ten,最终取出键和值

#获取键-值
scoundrel = {'name':'a','sex':'female','age':'ten'}
key1, values1=scoundrel.popitem()     #popitem()获取(和删除)字典中任意的键-值对,而且随机返回一项
print key1,values1                    #输出:age ten

  • 链式赋值
链式赋值(chained assignment)是将同一值赋给多个变量的捷径
x = y = somefunction()
y= somefunciton()
x = y

#注意 上面的语句与下面的语句不必定等价
x = somefunction()
y = somefunction()
  • 增量赋值
好比“x+=1”这种写法叫作增量赋值(augmented assinment),对于*、/、%等标准运算符都适用
x =2
x +=1
print x

fnord = 'foo'
fnord +='bar'
print fnord

#输出:
3
foobar
相关文章
相关标签/搜索