python - Python - 来自未排序文本的字典,列表理解?
问题描述
我希望更精通列表理解的人可以提供一些建议。
考虑以下数据集:
Onions,copper,manganese,magnesium,phosphorus
Tomatoes,copper,manganese,potassium
Garlic,manganese
Celery,manganese,potassium,sodium,salt
Bell Peppers,copper,manganese
Butter,sodium,salt
Eggplant,copper,manganese
Grapes,copper,manganese,potassium
我需要制定一个字典,使得关键是矿物质,而价值是一组含有该矿物质的食物 - 就像这样:
{'copper': {'Tomatoes', 'Onions', 'Bell Peppers', 'Eggplant'}, 'maganeese': {'Onions', 'Tomatoes', 'Garlic', 'Celery', 'Bell Peppers', 'Eggplant', 'Grapes'}... etc.}
您会注意到食物位于第一个位置,然后是它所含的矿物质。
我想我可能需要将食物和矿物质分成两个列表,食物列表和矿物质列表。从逻辑上讲,我完全不知道如何完成这项任务。
with open ('file.txt', 'r') as fp:
D = dict()
food_list = []
mineral_list = []
for line in fp:
line = line.strip().split(",")
line = [x for x in line if x]
food_list.append(line[0])
print(food_list)
有人可以在这里推动正确的方向吗?
解决方案
你可以这样做:
import pprint
mineral_table = {}
with open("ip.txt") as infile:
for line in infile:
# split the line into vegetable and minerals
vegetable, *minerals = line.strip().split(',')
# for each mineral add the vegetable to the mineral list
for mineral in minerals:
mineral_table.setdefault(mineral, []).append(vegetable)
pprint.pprint(mineral_table)
输出
{'copper': ['Onions', 'Tomatoes', 'Bell Peppers'],
'magnesium': ['Onions'],
'manganese': ['Onions', 'Tomatoes', 'Garlic', 'Celery', 'Bell Peppers'],
'phosphorus': ['Onions'],
'potassium': ['Tomatoes', 'Celery'],
'salt': ['Celery'],
'sodium': ['Celery']}
该行:
# split the line into vegetable and minerals
vegetable, *minerals = line.strip().split(',')
使用扩展的可迭代解包。for 循环使用setdefault,来自文档:
如果键在字典中,则返回其值。如果不是,则插入值为默认值的键并返回默认值。默认默认为无。
推荐阅读
- c# - 为什么在我映射模型时自动映射器会出错?
- java - 使用 log4j2 在 Spring Boot 中自定义日志级别
- angular - Angular 8 - 材料自动完成 - mat-form-field
- javascript - 尝试在 localhost:3000 上的后端和 localhost:8080 上的前端之间建立 socket.io 连接时出现 CORS 错误
- python-3.x - 如何使用 cv2 python 生成视频
- javascript - 如何使用 jquery 将多个文本复制到剪贴板
- spring - 使用服务器 Apache CXF 和 IDE Spring Tool Suite 4 启动 Web 服务时出现错误
- python - 在 FLASK API 中提取特定的 JSON
- unity3d - Unity DOTS (ECS) 中的“FixedUpdate”在哪里?
- scala - 附加输出模式在带有 foreach 接收器的 Spark 结构化流中不起作用