在 Python 中,如何替换列表中的元素?其实 Python 并无自带 Replace 方法,只能自己编写循环或者使用列表解析的方法。
list和tuple
list和tuple都是 sequence
type
的一种,是有序列表,其内置的方法都相似。举例来说,有 l
和 t
分别保存
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的概念。