Python数据结构:列表、字典的增删查操作实例
在Python中,列表(List)和字典(Dictionary)都是常用的数据结构。以下是这两种数据结构的增删查操作实例:
- 列表的增删查操作:
增(Add):
fruits = ['apple', 'banana', 'orange']
fruits.append('grape') # 添加元素到列表末尾
print(fruits) # 输出:['apple', 'banana', 'orange', 'grape']
删(Delete):
index_to_delete = 2 # 删除索引为2的元素
fruits.pop(index_to_delete) # 通过索引删除元素
print(fruits) # 输出:['apple', 'banana', 'orange', 'grape']
查(Search):
search_term = 'grape' # 搜索内容
if search_term in fruits:
print(f"'{search_term}'' found in the list.")
else:
print(f"'{search_term}'' not found in the list.")
- 字典的增删查操作:
- 增(Add):
```python
person = {‘name’: ‘Alice’, ‘age’: 30, ‘job’: ‘Engineer’}
新增键值对
person[‘city’] = ‘New York’
print(person) # 输出:{‘name’: ‘Alice’, ‘age’: 30, ‘job’: ‘Engineer’, ‘city’: ‘New York’}
- 删(Delete):
```python
key_to_delete = 'city' # 删除的键
if key_to_delete in person:
del person[key_to_delete]
else:
print(f"'{key_to_delete}'' not found in the dictionary, no deletion performed.")
print(person) # 输出:{'name': 'Alice', 'age': 30, 'job': 'Engineer'}
- 查(Search):
```python
search_term = ‘age’ # 搜索内容
if search_term in person:
print(f”‘{search_term}’’ found in the dictionary: {person[search_term]}}”)
else:
print(f”‘{search_term}’’ not found in the dictionary.”)
print(person) # 输出:{‘name’: ‘Alice’, ‘age’: 30, ‘job’: ‘Engineer’}
```
这些例子展示了如何在Python中操作列表和字典,包括增删查等基本操作。
还没有评论,来说两句吧...