【问题标题】:Python dictionaries Filtering stuff outPython字典过滤掉的东西
【发布时间】:2017-11-24 19:47:14
【问题描述】:

我在课堂实验室工作,但我有点卡住了,例如我有一个包含键和值的字典,这是另一个字典。

字典A:

dict_a = {
    1: {
        'Engine': 4,
        'Speed': 749,
        'max_speed': 1140,
        'name': 'Ship1',
    },

    2: {
        'Engine': 2,
        'Speed': 600,
        'max_speed': 900,
        'name': 'B777',
    },

    3: {
        'Engine': 4,
        'Speed': 1130,
        'max_speed': 1200,
        'name': 'Air_max',
    }
}

我正在尝试编写一个函数,该函数将接受两个参数(字典 A 和过滤字典)例如:

filter = {
    'Engine' :4,
    'name': 'Air_max',
}

此函数应返回一个列表,其中包含具有值 > 或等于过滤器的字典:

这只是一个例子。因为我只需要一个提示想法如何做到这一点。实际上,我的字典 A 非常大。

到目前为止,我有这个看起来不正确:

filtered = {
    'Engine':   2,
    'Speed':  300,
    'Type': 'Electric'
}

result = []
for k, v in full_data.items():
    for i, s in v.items():
        for a, b in filtered.items():
            if v[i] >= filtered[a]:
                result.append(v)
filtered_result = []
for each in result:
    if each not in filtered_result:
        filtered_result.append(each)
filtered_result[:3]

【问题讨论】:

  • 看起来你的“字典”违背了字典的目的,如果你必须遍历它们。
  • 您似乎想要dicts 中的list 而不是dicts 中的dict,其中键基本上只是索引。
  • 你的过滤代码有什么问题?它根本不起作用吗?是不是太慢了?它会产生什么样的结果?
  • @Blurp 我正在返回未过滤的字典列表。
  • @MooingRawr 不,我不想要代码,我只是想要我做错了什么。以及如何解决它。

标签: python loops dictionary iteration


【解决方案1】:

老实说,这部分似乎有点乱:

for k, v in full_data.items():
    for i, s in v.items():
        for a, b in filtered.items():
            if v[i] >= filtered[a]:
                result.append(v)

kv 标识符非常棒、简短且惯用。 is 的则更少。我怀疑您在写filtered 时是指filter。无论如何,我敦促您编写一个辅助函数,一个谓词is_wanted(data, filter),当满足过滤条件时返回True。您将能够独立于循环测试辅助函数。

然后返回到现在将调用谓词的循环,并考虑为变量提供更具描述性的名称。总的来说,您似乎走在了正确的轨道上。

【讨论】:

    【解决方案2】:

    你可以试试这个:

    filter = {
    'Engine' :4,
    'name': 'Air_max',
    }
    new_dict_a = [{a:b} for a, b in dict_a.items() if b['Engine'] >= filter['Engine']]
    

    输出:

    [{1: {'Engine': 4, 'max_speed': 1140, 'Speed': 749, 'name': 'Ship1'}}, {3: {'Engine': 4, 'max_speed': 1200, 'Speed': 1130, 'name': 'Air_max'}}]
    

    如果你想要字典而不是列表:

    new_dict_a = {a:b for a, b in dict_a.items() if b['Engine'] >= filter['Engine']}
    

    输出:

    {1: {'Engine': 4, 'max_speed': 1140, 'Speed': 749, 'name': 'Ship1'}, 3: {'Engine': 4, 'max_speed': 1200, 'Speed': 1130, 'name': 'Air_max'}}
    

    【讨论】:

    • 感谢您的回答。但是如果过滤器 dic 不固定怎么办,我的意思是它取决于用于提供 dic 的键和值。并且用户可以选择跳过引擎。并且可以将购买过滤为价值。
    猜你喜欢
    • 2022-01-23
    • 2020-03-19
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    相关资源
    最近更新 更多