2015年4月26日星期日

Python List和Tuple的区别

  面试中老是会问这个,还问使用场景,不过我一般只用list很少使用tuple,
没读过源码,简单的可以从以下几个方面说:
  1.列表里的内容是可以改变的,增删改都可以,tuple则不行:
>>> alist = [1,2,3,4]
>>> atuple = (1,2,3,4)
>>> atuple.append(1)
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'tuple' object has no attribute 'append'
>>> dir(atuple)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>> dir(alist)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
可以看出tuple根本没有修改的方法.
2.在Python中,字典的key必须是可哈希的,不可变的,所以tuple可以作为字典的键,而list则不行:

>>> adict = {}
>>> atuple = (1,2,3)
>>> adict[atuple] = 'ok'
>>> adict
{(1, 2, 3): 'ok'}
>>> alist = [1,2,3]
>>> adict[alist] = 'not ok'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
3.对于使用场景,tuple适合一些只读数据,如Python连接MySQL得到的结果就是使用tuple,
而list则在列表长度不固定或者需要有变动的数据中使用,另外,tuple的性能要比list好一些,
tuple比list更省内存:


>>> a = list(xrange(100000))
>>> a.__sizeof__()
900088
>>> b = tuple(xrange(100000))
>>> b.__sizeof__()
800024
而且更快,具体测试方法,参考stackoverflow

没有评论:

发表评论