网站首页 > 基础教程 正文
嵌套是 Python 中的一个高级概念,可以将多个字典存储在一个列表中,或者将一个项目列表作为字典中的值存储。
这允许高度灵活的数据结构。
词典列表:
您可能需要管理多个同类对象,例如游戏中的一组外星人。
您可以将它们全部存储在一个列表中,而不是为每个对象创建单独的字典。
例如,您可以将三个外星人的详细信息存储在字典列表中,如下所示:
# Create three dictionaries representing different aliens
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
# Store the dictionaries in a list
aliens = [alien_0, alien_1, alien_2]
# Loop through the list and print each alien
for alien in aliens:
print(alien)
>>
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
甚至可以自动生成大量类似的对象。以下是创建 30 个绿色外星人舰队的方法:
# Make an empty list to store aliens
aliens = []
# Generate 30 green aliens
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# Show the first 5 aliens
for alien in aliens[:5]:
print(alien)
print(f"Total number of aliens: {len(aliens)}")
>>
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
Total number of aliens: 30
该程序创建 30 个相同的外国人并打印前 5 个。我
如果你想修改其中的一些(比如,把前三个改成黄色的 aliens),你可以使用 if 语句来选择性地修改它们:
# Make an empty list for storing aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range (30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
# Show the first 5 aliens.
for alien in aliens[:5]:
print(alien)
>>
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
这会将前三个外星人更新为黄色的中速外星人,价值 10 分。
字典中的列表:
有时,您可能需要在字典中存储单个键的多个值。
例如,在订购披萨时,您可能希望同时存储 pist type 和 toppings 列表:
# Store information about a pizza
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# Summarize the order
print(f"You ordered a {pizza['crust']}-crust pizza with the following toppings:")
for topping in pizza['toppings']:
print(f"\t{topping}")
>>
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
字典中的字典:
有时,您可能希望将一个词典嵌套在另一个词典中。
例如,如果您正在管理网站上的用户配置文件,则可以存储每个用户的详细信息,如下所示:
# Dictionary of users
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
# Loop through users and print information
for username, user_info in users.items():
print(f"\nUsername: {username}")
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']
print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")
>>
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
嵌套列表和字典允许使用复杂和动态的数据结构,从而更容易存储和操作相关信息。但是,请注意不要嵌套得太深,因为这会使代码难以管理。
- 上一篇: 一文掌握Python 字典遍历的8种方法
- 下一篇: python字典查找和搜索的方法
猜你喜欢
- 2025-01-07 Python从入门到放弃-详解列表、元组和字典
- 2025-01-07 python 中字典如何进行复制
- 2025-01-07 python入门023:字典嵌套
- 2025-01-07 掌握Python字典的12个例子
- 2025-01-07 使用Python 获取多级字典(Json)格式所有Key、Value
- 2025-01-07 简单学Python——字典的操作1(增加、更改和删除字典元素)
- 2025-01-07 Python之容器拾遗:Python就是包裹在一堆语法糖中的字典
- 2025-01-07 深入了解python字典的有序特性
- 2025-01-07 如何在 Python 中以列表形式返回字典的键
- 2025-01-07 解锁Python字典合并:多种方法解析
- 05-22Linux cron任务计划
- 05-22测试人员如何在linux服务器中查询mysql日志?
- 05-22Nginx命令最全详解(29个最常用命令)
- 05-22初识自动化网络编排器NSO,轻松配置复杂的多厂商网络
- 05-22Nacos在企业生产中如何使用集群环境?
- 05-22如何从 MySQL 错误日志中排查数据库故障
- 05-22Linux面试最高频的5个基本问题
- 05-22linux网卡混杂模式
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- deletesql (62)
- c++模板 (62)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- console.table (62)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)