Python数据结构:列表、字典的增删查操作实例

原创 系统管理员 2025-01-10 06:15 54阅读 0赞

在Python中,列表(List)和字典(Dictionary)都是常用的数据结构。以下是这两种数据结构的增删查操作实例:

  1. 列表的增删查操作:
  • 增(Add):

    1. fruits = ['apple', 'banana', 'orange']
    2. fruits.append('grape') # 添加元素到列表末尾
    3. print(fruits) # 输出:['apple', 'banana', 'orange', 'grape']
  • 删(Delete):

    1. index_to_delete = 2 # 删除索引为2的元素
    2. fruits.pop(index_to_delete) # 通过索引删除元素
    3. print(fruits) # 输出:['apple', 'banana', 'orange', 'grape']
  • 查(Search):

    1. search_term = 'grape' # 搜索内容
    2. if search_term in fruits:
    3. print(f"'{search_term}'' found in the list.")
    4. else:
    5. print(f"'{search_term}'' not found in the list.")
  1. 字典的增删查操作:
  • 增(Add):
    ```python
    person = {‘name’: ‘Alice’, ‘age’: 30, ‘job’: ‘Engineer’}

新增键值对

person[‘city’] = ‘New York’

print(person) # 输出:{‘name’: ‘Alice’, ‘age’: 30, ‘job’: ‘Engineer’, ‘city’: ‘New York’}

  1. - 删(Delete):
  2. ```python
  3. key_to_delete = 'city' # 删除的键
  4. if key_to_delete in person:
  5. del person[key_to_delete]
  6. else:
  7. print(f"'{key_to_delete}'' not found in the dictionary, no deletion performed.")
  8. 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中操作列表和字典,包括增删查等基本操作。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,54人围观)

还没有评论,来说两句吧...

相关阅读