文章目录
-
-
- [1. List 操作](#1. List 操作)
- [2. JSON 操作](#2. JSON 操作)
- [3. Dict 操作](#3. Dict 操作)
-
下面是分别演示 list
、json
、dict
操作
1. List 操作
python
my_list=[]
# List 操作示例
my_list = [1, 2, 3, "apple", True]
# 添加元素
my_list.append("new item") # [1, 2, 3, "apple", True, "new item"]
# 修改元素
my_list[1] = "banana" # [1, "banana", 3, "apple", True, "new item"]
# 删除元素
my_list.remove("banana") # [1, 3, "apple", True, "new item"]
# 列表长度
length = len(my_list) # 5
# 遍历列表
for item in my_list:
print(item)
2. JSON 操作
python
import json
# 字典转 JSON 字符串
my_dict = {"name": "Alice", "age": 30, "is_student": False}
json_str = json.dumps(my_dict, indent=4, ensure_ascii=False) # '{"name": "Alice", "age": 30, "is_student": false}'
print(json_str)
# JSON 字符串转字典
json_str = '{"name": "Alice", "age": 30, "is_student": false}'
my_dict = json.loads(json_str) # {'name': 'Alice', 'age': 30, 'is_student': False}
print(my_dict)
3. Dict 操作
python
# Dict 操作示例
my_dict = {"name": "Alice", "age": 30, "is_student": False}
# 访问元素
name = my_dict["name"] # "Alice"
# 修改元素
my_dict["age"] = 31 # {"name": "Alice", "age": 31, "is_student": False}
# 添加键值对
my_dict["city"] = "New York" # {"name": "Alice", "age": 31, "is_student": False, "city": "New York"}
# 删除键值对
del my_dict["is_student"] # {"name": "Alice", "age": 31, "city": "New York"}
# 遍历字典
for key, value in my_dict.items():
print(f"{key}: {value}")