# === 列表与字典 ===
# 1. 列表(list):按顺序存放一组数据
print("--- 列表 ---")
fruits = ["苹果", "香蕉", "橘子", "葡萄"]
print(fruits) # 打印整个列表
print(fruits[0]) # 取第一个元素(索引从0开始)
print(fruits[2]) # 取第三个
print(fruits[-1]) # 取最后一个
print()
# 2. 列表的常用操作
fruits.append("西瓜") # 末尾添加
print(f"添加后: {fruits}")
fruits.insert(1, "芒果") # 在索引1的位置插入
print(f"插入后: {fruits}")
fruits.remove("香蕉") # 删除指定元素
print(f"删除后: {fruits}")
popped = fruits.pop() # 弹出最后一个元素
print(f"弹出的是: {popped}")
print(f"弹出后: {fruits}")
print(f"列表长度: {len(fruits)}") # 长度
print()
# 3. 列表遍历
for fruit in fruits:
print(f"我喜欢{fruit}")
print()
# 4. 字典(dict):用键值对存放数据
print("--- 字典 ---")
student = {
"name": "火鸟",
"age": 25,
"course": "Python",
"level": "初学者"
}
print(student)
print(student["name"]) # 用键取值
print(student["course"])
print()
# 5. 字典的常用操作
student["score"] = 95 # 添加新键值对
print(f"添加分数: {student}")
student["age"] = 26 # 修改已有键的值
print(f"修改年龄: {student}")
del student["level"] # 删除键值对
print(f"删除等级: {student}")
print(f"所有键: {list(student.keys())}")
print(f"所有值: {list(student.values())}")
print()
# 6. 字典遍历
for key, value in student.items():
print(f"{key}: {value}")
print()
# 7. 实战:简单的通讯录
print("--- 通讯录 ---")
contacts = {}
while True:
print("\n1. 添加联系人")
print("2. 查找联系人")
print("3. 显示所有联系人")
print("4. 退出")
choice = input("请选择操作(1-4):")
if choice == "1":
name = input("姓名:")
phone = input("电话:")
contacts[name] = phone
print(f"已添加 {name}")
elif choice == "2":
name = input("要查找的姓名:")
if name in contacts:
print(f"{name}: {contacts[name]}")
else:
print("没有找到该联系人")
elif choice == "3":
if contacts:
for name, phone in contacts.items():
print(f"{name}: {phone}")
else:
print("通讯录为空")
elif choice == "4":
print("再见!")
break
else:
print("无效选择,请输入1-4")
未经允许不得转载:百花谷博客 » 跟着AI学Python 第4课:列表与字典

百花谷博客
微信关注,获取更多