Python常用添加/删除元素API的完整代码
作者:Elias不吃糖
这篇文章主要介绍了Python中list、dict和set三种常用数据类型的添加和删除元素API,并提供了示例代码,涵盖了append、insert、pop、remove、clear等关键操作方法,适合初学者快速掌握常用数据结构的使用技巧,需要的朋友可以参考下
Python 常用添加 / 删除元素 API
1. list 列表
| 操作 | API | 示例 |
|---|---|---|
| 尾部添加 | append(x) | arr.append(4) |
| 指定位置插入 | insert(i, x) | arr.insert(1, 99) |
| 添加多个元素 | extend(iterable) | arr.extend([5, 6]) |
| 删除最后一个 | pop() | arr.pop() |
| 删除指定下标 | pop(i) | arr.pop(0) |
| 删除指定值 | remove(x) | arr.remove(99) |
| 删除指定下标 | del arr[i] | del arr[1] |
| 清空 | clear() | arr.clear() |
示例:
arr = [1, 2, 3] arr.append(4) # [1, 2, 3, 4] arr.insert(1, 99) # [1, 99, 2, 3, 4] arr.extend([5, 6]) # [1, 99, 2, 3, 4, 5, 6] arr.pop() # 删除最后一个 arr.pop(0) # 删除下标 0 arr.remove(99) # 删除值 99
2. dict 字典
| 操作 | API | 示例 |
|---|---|---|
| 添加 / 修改 | dict[key] = value | mp["a"] = 1 |
| 删除指定 key | pop(key) | mp.pop("a") |
| 删除指定 key | del dict[key] | del mp["a"] |
| 安全删除 | pop(key, 默认值) | mp.pop("x", None) |
| 清空 | clear() | mp.clear() |
示例:
mp = {}
mp["a"] = 1
mp["b"] = 2
mp["a"] = 100 # 修改
mp.pop("b") # 删除 b
mp.pop("x", None) # x 不存在也不报错
3. set 集合
| 操作 | API | 示例 |
|---|---|---|
| 添加一个元素 | add(x) | s.add(4) |
| 添加多个元素 | update(iterable) | s.update([5, 6]) |
| 删除指定元素 | remove(x) | s.remove(3) |
| 安全删除 | discard(x) | s.discard(10) |
| 随机删除一个 | pop() | s.pop() |
| 清空 | clear() | s.clear() |
示例:
s = {1, 2, 3}
s.add(4)
s.update([5, 6])
s.remove(3) # 不存在会报错
s.discard(10) # 不存在不报错
4. 字符串 str
字符串不能直接修改,只能生成新字符串。
s = "abc"
s = s + "d" # "abcd"
s = s.replace("a", "x") # "xbcd"
错误写法:
s[0] = "x" # 错,字符串不可变
5. 栈 stack
Python 一般用 list 当栈。
| 操作 | API |
|---|---|
| 入栈 | append(x) |
| 出栈 | pop() |
stack = [] stack.append(1) stack.append(2) stack.pop() # 2
6. 队列 queue
推荐用 deque。
| 操作 | API |
|---|---|
| 入队 | append(x) |
| 出队 | popleft() |
from collections import deque q = deque() q.append(1) q.append(2) q.popleft() # 1
最常用记忆版
| 类型 | 添加 | 删除 |
|---|---|---|
list | append() / insert() / extend() | pop() / remove() |
dict | mp[key] = value | pop(key) / del mp[key] |
set | add() / update() | discard() / remove() |
stack | append() | pop() |
queue | append() | popleft() |
以上就是Python常用添加/删除元素API的完整代码的详细内容,更多关于Python常用添加/删除元素API的资料请关注脚本之家其它相关文章!
