# Python——可变类型与不可变类型（即为什么函数默认参数要用元组而非列表）

Python 的内建标准类型有一种分类标准是分为可变类型与不可变类型：

• 可变类型：列表、字典
• 不可变类型：数字、字符串、元组

>>> id(1),id(2)
(507098784, 507098816)
>>> a = 1
>>> id(a)
507098784
>>> a = 2
>>> id(2)
507098816

>>> b = [0]
>>> id(b)
171805000
>>> b[0] = 1
>>> id(b)
171805000

>>> b = [0]
>>> id(b[0])
507098752
>>> b[0] = 1
>>> id(b[0])
507098784

>>> def biggest(n, store=[0]):
store[0] = max(n, store[0])
return store[0]

>>> biggest(3)
3
>>> biggest(9)
9
>>> biggest(5)
9

import time
def dur( op=None, clock=[time.time()] ):
if op != None:
duration = time.time() - clock[0]
print '%s finished. Duration %.6f seconds.' % (op, duration)
clock[0] = time.time()

if __name__ == '__main__':
import array
dur()   # Initialise the timing clock

opt1 = array.array('H')
for i in range(1000):
for n in range(1000):
opt1.append(n)
dur('Array from append')

opt2 = array.array('H')
seq = range(1000)
for i in range(1000):
opt2.extend(seq)
dur('Array from list extend')

opt3 = array.array('H')
seq = array.array('H', range(1000))
for i in range(1000):
opt3.extend(seq)
dur('Array from array extend')

import time
def dur(op='Undefined',clock=[time.time()]):
duration = time.time() - clock[0]
print('%s finished\t Duration:%.6f seconds.'%(op,duration))
clock[0] = time.time()

if __name__ == '__main__':
import array
dur('Initialise')   # Initialise the timing clock

posted @ 2015-02-25 15:26 落叶落叶 阅读(...) 评论(...) 编辑 收藏