>>> nudge = 1
>>> wink = 2
>>> A,B = nudge,wink
>>> A,B
(1, 2)
>>> [C,D] = [nudge,wink]
>>> C,D
(1, 2)
>>> nudge = 1
>>> wink = 2
>>> [a,b,c] = (1,2,3)
>>> a,c
(1, 3)
>>> (a,b,c) = "ABC"
>>> a,c
('A', 'C')
###高级序列赋值语句模式
>>> string = 'SPAM'
>>> a,b,c,d = string #序列赋值需要两边的元素数目相等
>>> a,d
('S', 'M')
>>>
>>> a,b,c = string #不相等则报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 3)
>>> seq = [1,2,3,4]
>>> a,b,c,d = seq #两边元素个数要对应
>>> print(a,b,c,d)
1 2 3 4
>>> a,b = seq #元素不对应就报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>>
>>> a, *b = seq #序列解包,将没有赋值给其他变量的内容全部接收
>>> a
1
>>> b
[2, 3, 4]
>>> *a,b = seq
>>> a
[1, 2, 3]
>>> b
4
>>> a,*b,c = seq #先给其他变量赋值,剩下的再赋值给带星号的变量
>>> a
1
>>> b
[2, 3]
>>> c
4
>>> a,*b = 'spam'
>>> a
's'
>>> b
['p', 'a', 'm']
>>> seq
[1, 2, 3, 4]
>>> a,b,c,*d = seq #带星号的名称可能只匹配单个的项,但是总是向其赋值一个列表
>>> print(a,b,c,d)
1 2 3 [4]
>>> seq
[1, 2, 3, 4]
>>> a,b,c,d,*e = seq #没有剩下的内容进行匹配,会被赋值一个空的列表
>>> print(a,b,c,d,e)
1 2 3 4 []
>>> a,b,*e,c,d = seq
>>> print(a,b,c,d,e)
1 2 3 4 []
>>> seq
[1, 2, 3, 4]
>>> a,*b,c,*d = seq #有多个带星号的名称
File "<stdin>", line 1
SyntaxError: two starred expressions in assignment
>>> a,b = seq #值少了而没有带星号的名称
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> *a = seq #带星号的名称自身没有编写到一个序列中
File "<stdin>", line 1
SyntaxError: starred assignment target must be in a list or tuple
>>> *a, = seq
>>> a
[1, 2, 3, 4]
>>> a = b = c = 'spam'
>>> a,b,c
('spam', 'spam', 'spam')
#等价于
>>> c = 'spam'
>>> b = c
>>> a = b
注意:这里是一个对象由三个变量共享引用,这种行为对于不可变类型而言没有问题.
>>> a = b = 0
>>> b = b + 1
>>> a,b
(0, 1)
>>> a = b = []
>>> b.append(22)
>>> a,b
([22], [22])
>>> a = []
>>> b = []
>>> b.append(42)
>>> a,b
([], [42])
>>> L = [1,2]
>>> M = L
>>> L = L + [3,4] #传统的赋值,产生新的对象
>>> L,M
([1, 2, 3, 4], [1, 2])
>>> L = [1,2]
>>> M = L
>>> L += [3,4] #使用增强赋值,没有产生新的对象,在原处修改对象
>>> L,M
([1, 2, 3, 4], [1, 2, 3, 4])
原型: print([object, …][, sep = ’ ‘][,end = ‘\n’][, file = sys.stdout])
Python 2.6 | Python3.0 |
---|---|
print x, y | print(x, y) |
print x,y, | print(x, y, end = ”) |
print >> afile, x, y | print(x, y, file = afile) |
>>> import sys
>>> temp = sys.stdout
>>> sys.stdout = open('log.txt','a') #重定向输出流
>>> print('spam')
>>> print(1,2,3)
>>> sys.stdout.close()
>>> sys.stdout = temp #恢复输出流
>>> print('back here')
back here
>>> print(open('log.txt').read())
spam
1 2 3
>>> log = open('log.txt','w')
>>> print(1,2,3,file = log)
>>> print(4,5,6,file = log)
>>> log.close()
>>> print(7,8,9)
7 8 9
>>> print(open('log.txt').read())
1 2 3
4 5 6
from __future__import print_function