标签:python
赋值语句的基本操作在前面的章节已经说到过,现在我们来说说赋值到高级应用
第一节说的是序列赋值
>>> a= 1 >>> b=2 >>> c,d=a,b >>> c,d (1, 2) >>> [c,d]=[a,b] >>> c 1 >>> c,d (1, 2) >>>
>>> a= 1 >>> b=2 >>> b,a=a,b >>> a 2 >>> b 1 >>> a,b (2, 1) >>>上面的这种元组使用技巧是经常使用的
而且,上面的技巧不单适合整个元组,而且还适合部分的赋值
>>> (a,b,c)=(1,2,3) >>> a,b (1, 2) >>> b,c (2, 3) >>> a,b,c (1, 2, 3) >>> a 1 >>>
我们可以使用=将两侧混合相匹配,不过右边元素的数目必须跟左边的一致
>>> a,b,c,d='abcd'
>>> a,b,c,d
('a', 'b', 'c', 'd')
>>> a,b,c='abcd'
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
a,b,c='abcd'
ValueError: too many values to unpack (expected 3)
>>> >>> a,b,c=string[0],string[1],string[2]
>>> a,b,c
('a', 'b', 'c')
>>> a,b,c=list(string[:2])+[string[2:]]
>>> a,b,c
('a', 'b', 'cd')
>>> >>> ((a,b),c)=('ab','cd')
>>> a,b,c
('a', 'b', 'cd')
>>> 在上面我们看到,左右两侧的数目必须一致,但是也是有其他办法打破这个的
我们可以使用*来作为通配符,代表余下的数据项
>>> a,*b='abcd'
>>> a,b
('a', ['b', 'c', 'd'])
>>> 上面的a只是代表第一项,余下的都赋值给b
同理:
>>> *a,b='abcd' >>> a,b (['a', 'b', 'c'], 'd') >>>
>>> *a,b,c='abcd' >>> a,b,c (['a', 'b'], 'c', 'd') >>>这个序列扩展包对于所有序列类型都有效
>>> a,*b=(1,2,3,4) >>> a,b (1, [2, 3, 4]) >>> a,*b=[1,2,3,4] >>> a,b (1, [2, 3, 4]) >>>
>>> a,b,c,d,*e=(1,2,3,4)
>>> a,b,c,d,e
(1, 2, 3, 4, [])
>>> a,b,c,d,*e='abcd'
>>> a,b,c,d,e
('a', 'b', 'c', 'd', [])
>>> >>> a,*b,*c,d,*e='abcd'
SyntaxError: two starred expressions in assignment
>>> a,b,c,d,e='abcd'
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
a,b,c,d,e='abcd'
ValueError: need more than 4 values to unpack
>>> *a='abcd'
SyntaxError: starred assignment target must be in a list or tuple
>>>
>>> *a,='abcd' >>> a ['a', 'b', 'c', 'd'] >>>
就说到这里,谢谢大家
------------------------------------------------------------------
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:python
原文地址:http://blog.csdn.net/raylee2007/article/details/48132253