发新话题
打印

【求助】Python 中 list 和 tuple 的区别?

【求助】Python 中 list 和 tuple 的区别?

看了几天 Python,被 list 和 tuple 给搞糊涂了,除了输出格式不同之外,它们还有什么区别?什么时候该用 list,什么时候该用 tuple 呢?      
'
◆ 发帖时请【突出主题】, 以便您的问题能够及时得到回复
◆ 发帖时请将您的【代码】或者【脚本】写在 [code] 和 [/code] 中间

TOP

研究了一下,tuple 的元素不能被修改,而 list 则可以:
复制内容到剪贴板
代码:
[color=blue]-(guest@mac:tty1)-(tmp)-
[21827 0] %[/color] python
Python 2.3 (#1, Sep 13 2003, 00:49:11)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1, 2, 3, 4
>>> a
(1, 2, 3, 4)
>>> a = (1, 2, 3, 4)
>>> a
(1, 2, 3, 4)
>>> a[0] = 11
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> a = [1, 2, 3, 4]
>>> a
[1, 2, 3, 4]
>>> a[0] = 11
>>> a
[11, 2, 3, 4]
>>> ^D
[color=blue]-(guest@mac:tty1)-(tmp)-
[21827 0] %[/color]
      
'
◆ 发帖时请【突出主题】, 以便您的问题能够及时得到回复
◆ 发帖时请将您的【代码】或者【脚本】写在 [code] 和 [/code] 中间

TOP

From <<Core Python Programming>>:

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ), and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of for now as "read-only" lists. Subsets can be taken with the slice operator ( [] and [ : ] ) in the same manner as strings.      
'
◆ 发帖时请【突出主题】, 以便您的问题能够及时得到回复
◆ 发帖时请将您的【代码】或者【脚本】写在 [code] 和 [/code] 中间

TOP

发新话题