【问题标题】:Python - Dictionary from unsorted text, list comprehension?Python - 来自未排序文本的字典,列表理解?
【发布时间】:2021-02-23 16:16:33
【问题描述】:

我希望更精通列表理解的人可以提供一些建议。

考虑以下数据集:

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)

任何人都可以在这里推动正确的方向吗?

【问题讨论】:

  • 你所拥有的看起来很合理。它做错了什么或者你还需要做什么?

标签: python python-3.x dictionary list-comprehension


【解决方案1】:

你可以这样做:

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(',')

使用extended iterable unpacking。 for 循环使用setdefault,来自文档:

如果键在字典中,则返回其值。如果没有,请插入密钥 默认值并返回默认值。默认默认为无。

【讨论】:

  • 没关系,明白了!只需要使用集合而不是列表...所以更改为 Mineral_table.setdefault(mineral, set()).add(vegetable) 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
  • 2012-11-26
相关资源
最近更新 更多