[英]Filtering a dictionary with another dictionary containing multiple items
我有一本字典,我想用另一本字典(其中有“过滤器选项”显示在这篇文章的一半下方)进行过滤。 我可以为单个项目而不是整个字典找出一些东西...我已经看了一会儿了,但其他答案仅是一个条目的过滤器(字典理解很好地解决了)
这是我到目前为止对单项字典过滤器所做的,即
filter_options = {
'Attack': 25}
for kfo, vfo in filter_options.iteritems():
for kp, vp in pokers.iteritems():
if vp[kfo] >= vfo:
print pokedex[kp]
它有效,但我无法弄清楚它是否可以过滤多个项目
这是字典的截断版本
pokedex = {1: {'Attack': 49.0,
'Defense': 49.0,
'HP': 45.0,
'Name': 'Bulbasaur',
'PokedexNumber': 1.0,
'SpecialAttack': 65.0,
'SpecialDefense': 65.0,
'Speed': 45.0,
'Total': 318.0,
'Type': 'GrassPoison'},
2: {'Attack': 62.0,
'Defense': 63.0,
'HP': 60.0,
'Name': 'Ivysaur',
'PokedexNumber': 2.0,
'SpecialAttack': 80.0,
'SpecialDefense': 80.0,
'Speed': 60.0,
'Total': 405.0,
'Type': 'GrassPoison'},
3: {'Attack': 82.0,
'Defense': 83.0,
'HP': 80.0,
'Name': 'Venusaur',
'PokedexNumber': 3.0,
'SpecialAttack': 100.0,
'SpecialDefense': 100.0,
'Speed': 80.0,
'Total': 525.0,
'Type': 'GrassPoison'}}
# Only filter based on parameters passed
filter_options = {
'Attack': 25,
'Defense': 30,
'Type': 'Electric'
}
例如,返回攻击> = 25,防御> = 30且类型==“ Electric”的记录。还要预料到也可以传递其他参数,例如“ SpecialAttack”,“ Speed”等。
输出示例:
[{'Attack': 30.0,
'Defense': 50.0,
'HP': 40.0,
'Name': 'Voltorb',
'SpecialAttack': 55.0,
'SpecialDefense': 55.0,
'Speed': 100.0,
'Total': 330.0,
'Type': 'Electric'},
{'Attack': 30.0,
'Defense': 33.0,
'HP': 32.0,
'Name': 'Pikachu',
'SpecialAttack': 55.0,
'SpecialDefense': 55.0,
'Speed': 100.0,
'Total': 330.0,
'Type': 'Electric'},
... etc
]
我会按照以下原则将其粘贴到一个函数中
def filtered_pokedex(pokedex_data, filter=filter_options):
....etc
但可以自己解决
如果它需要更好地解释或编辑,请让我知道欢呼...关于堆栈交换的第一个问题,希望我提供了足够的信息
干杯
在此情况下all
使用。 检查该值是数字类型还是字符串类型,并相应地更改条件。
def foo(vp, k, v):
return vp[k] > v if isinstance(v, (int, float)) else vp[k] == v
for kp, vp in pokedex.iteritems():
if all(foo(vp, k, v) for k, v in filter_options.iteritems()):
print vp
我定义了一个函数foo
来处理检查,因为它整理了代码。
这是熊猫的解决方案:
import pandas as pd
df = pd.DataFrame(pokedex).T
df # change last entry to Type = "Electric" for demo output.
Attack Defense HP Name ... Type
1 49 49 45 Bulbasaur ... GrassPoison
2 62 63 60 Ivysaur ... GrassPoison
3 82 83 80 Venusaur ... Electric
现在基于filter_options
构建一个布尔掩码:
mask = [True] * len(df)
for key in filter_options:
if isinstance(filter_options[key], int):
mask = mask & (df[key] >= filter_options[key]).values
elif isinstance(filter_options[key], str):
mask = mask & (df[key] == filter_options[key]).values
else:
continue
df.loc[mask]
Attack Defense HP Name ... Type
3 82 83 80 Venusaur ... Electric
在Python中回答您的问题:对每个选项递归过滤“单个过滤”的结果,直到产生结果。 为了使单个过滤器的大小更好,将filter_options重组为包含更多信息。
但是当允许不同的操作类型时,它变得复杂。 该问题并未明确询问,但确实超出了第一个示例。 在一组过滤器中允许多种操作类型的最简单解决方案是“开关”之类的结构,其中包含每种可能操作的功能,但“更好”的解决方案是将操作员本身从标准操作员库中传递出去。
# pokedex = ...
filter_options = [
{
'attribute': 'Attack',
'operator': '>=',
'value': 25,
},
{
'attribute': 'Defense',
'operator': '>=',
'value': 30,
},
{
'attribute': 'Type',
'operator': '==',
'value': 'Electric',
},
]
# Better to use: https://docs.python.org/2/library/operator.html
operators = {
'<': lambda a, b: a < b,
'>': lambda a, b: a > b,
'==': lambda a, b: a == b,
'<=': lambda a, b: a <= b,
'>=': lambda a, b: a >= b,
}
def filter_single(attribute, operator, value, pokedex=pokedex):
result = {}
for number, pokemon in pokedex.iteritems():
if operators[operator](pokemon[attribute], value):
result[number] = pokemon
return result
def filter(filter_options, pokedex=pokedex):
result = filter_single(
filter_options[0]['attribute'],
filter_options[0]['operator'],
filter_options[0]['value'],
pokedex,
)
for option in filter_options[1:]:
result = filter_single(
option['attribute'],
option['operator'],
option['value'],
result,
)
return result
print filter(filter_options)
该代码已在Python 3上进行了测试,但应在2.7上运行。 将print
替换为print()
,将.iteritems()
替换为.items()
以转换为Python3。
使用结构化查询语言(SQL)可以轻松考虑这种类型的查询。 将数据结构连接到思维模式是SQL的目的之一。
例:
SELECT * FROM pokedex
WHERE attack >= 25
AND defense >= 30
AND type == 'Electric';
PS:我认为问题的描述缺少“ pokers”变量似乎是所有口袋妖怪可用的属性,但是如果假定过滤器选项始终是有效的属性名称,则不需要这样做。 使用FilterOption类是强制使用有效过滤器的一种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.