python list 插入重复元素不会覆盖,见以下测试:
bash
Python 3.10.12 (main) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1, 2, 3]
>>> print(a)
[1, 2, 3]
>>> a.append(4)
>>> print(a)
[1, 2, 3, 4]
>>> a.append(2)
>>> print(a)
[1, 2, 3, 4, 2]
>>> a.append('6')
>>> print(a)
[1, 2, 3, 4, 2, '6']
>>> a.append('6')
>>> print(a)
[1, 2, 3, 4, 2, '6', '6']
如果需要重复元素不被添加,需自行判断元素是否存在,见以下demo:
bash
if item not in object_list:
object_list.append(item)
python 列表基本操作
Python 表达式 | 结果 | 描述 |
---|---|---|
len([1, 2, 3]) | 3 | 长度 |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | 组合 |
['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | 重复 |
3 in [1, 2, 3] | True | 元素是否存在于列表中 |
for x in [1, 2, 3]: print x, | 1 2 3 | 迭代 |