python 里list, tuple, set, dict的异同

2014-04-08
标签: PYTHON
本文发布至今已有10年零14天,可能不再适用,请谨慎对待。

在 Python 中,如何替换列表中的元素?其实 Python 并无自带 Replace 方法,只能自己编写循环或者使用列表解析的方法。

list和tuple

list和tuple都是 sequence type 的一种,是有序列表,其内置的方法都相似。举例来说,有 lt 分别保存 list 和 tuple

t = (1, 2, 3, 4, 5)

比如支持in运算,

    >>> 1 in l
    True
    >>> 1 in t
    True
    >>> 

元素有坐标,

    >>> l.index(2)
    1
    >>> t.index(2)
    1
    >>>

支持index

    >>> l[3]
    4
    >>> t[3]
    4
    >>> 

支持slicing

    >>> l[2:4]
    [3, 4]
    >>> t[2:4]
    (3, 4)
    >>> 

list和tuple的区别:list是mutable的对象,内容可以更改,tuple则不是,所以是hashable的。关于mutable和hashable的概念,可以参考`[Python 里 immutable和hashable的概念](https://www.lfhacks.com/tech/immutable-hashable-in-python/ "Python 里 immutable和hashable的概念")Python
里 immutable和hashable的概念`</txp:permlink>

所以,一些list有的方法,在tuple里就不能实现:

    >>> l.append(6)
    >>> l
    [1, 2, 3, 4, 5, 6]
    >>> t.append(6)
    Traceback (most recent call last):
        File "<pyshell#12>", line 1, in <module>
            t.append(6)
    AttributeError: 'tuple' object has no attribute 'append'</font> 
    >>>
    >>> l.pop()
    6
    >>> t.pop()
    Traceback (most recent call last):
        File "<pyshell#14>", line 1, in <module>
            t.pop()
    AttributeError: 'tuple' object has no attribute 'pop'</font> 
    >>> 

## set和dict

set和dict的都是无序列表,没有index的概念。

如果您对本站内容有疑问或者寻求合作,欢迎 联系邮箱邮箱已到剪贴板

标签: PYTHON

欢迎转载本文,惟请保留 原文出处 ,且不得用于商业用途。
本站 是个人网站,若无特别说明,所刊文章均为原创,并采用 署名协议 CC-BY-NC 授权。