Python中复制语法有6种
Basic Form
>>>spam = ‘spam‘
Tuple assignment
>>>spam, ham = ‘spam‘, ‘ham‘
List assignmen
>>>[spam, ham] = [‘spam‘, ‘ham‘]
Sequence assignment
>>>a, b,c,d = ‘spam‘
Extended sequence unpacking(Python 3.X)
>>>a, *b = ‘spam‘ >>>a ‘s‘ >>>b # b赋值的结果是一个list [‘p‘, ‘a‘, ‘m‘] >>>a, *b, c = ‘spam‘ >>>a ‘s‘ >>>b [‘p‘, ‘a‘] >>>c ‘m‘
对于这种复制方式,需要注意五点:
1 对于有*号变量的赋值结果,总是一个list,即使只包含一个元素
2 如果没有剩余的值赋给有*号的变量,那就是一个空list
>>>>a, b, c, *e, d = ‘spam‘ >>>a ‘s‘ >>>b ‘p‘ >>>c ‘a‘ >>>d ‘m‘ >>>e # 与*变量的位置无关 []
3 如果一条赋值语句中出现2个或者2个以上的*变量,会报错
4 变量个数和值的个数不匹配,也会报错
>>>a, b, c, d,e = ‘spam‘ # 值个数太少 ValueError: not enough values to unpack (expected 5, got 4) >>>a, b = ‘spam‘ # 变量个数太少 ValueError: too many values to unpack(expected 2)
5 带*号变量不在一个sequence中,也会报错
>>>*a = ‘spam‘ SyntaxError: starred assignment target must be in a list or tuple >>>*a, = ‘spam‘ # 这样OK >>>a [‘s‘, ‘p‘, ‘a‘, ‘m‘]
Augmented assignment
>>>spams = 42 >>>spams += 42 >>>spams 84
Augmented assignment有3个优势:
1 简洁,可以少打字,哈哈
2 对于X += Y的形式,如果X是一个很复杂的对象,那么Augmented assignment对X只运行一次代码,而如果写成X = X + Y的形式,对于X的代码会运行两次
3 在某些情形下,X+=Y是一种优化
>>>L = [1, 2] >>>L = L + [3, 4] # 这种形式的+会创建一个临时的,新的list,然后将L和要连接的数组copy进去,最后再把这个临时的,新的list赋值给L,效率低 >>>L [1, 2, 3, 4] >>>L = [1, 2] >>>L += [3, 4] # 这种形式直接改变L,不创建新对象,也不拷贝,效率高 >>>L [1, 2, 3, 4]
原文地址:https://www.cnblogs.com/chaoguo1234/p/9164313.html
时间: 2024-11-05 18:44:35