【发布时间】:2017-09-02 18:06:59
【问题描述】:
数据集:
data = [{'name':'kelly', 'attack':5, 'defense':10, 'country':'Germany'},
{'name':'louis', 'attack':21, 'defense': 12, 'country':'france'},
{'name':'ann', 'attack':43, 'defense':9, 'country':'Germany'}]
header = ['name', 'attack', 'defense', 'country']
filter_options = {'attack':4, 'defense':7, 'country':'Germany'}
我想写一个函数,data 是参数,filter_options 是函数的参数。即func(data, filter_options)
filter_options 将通过精确匹配过滤字符串类型值,和/或过滤大于或等于字典键参数的连续变量指定值。即我的答案应该是
answer = [{'name':'kelly', 'attack':5, 'defense':10, 'country':'Germany'},
{'name':'ann', 'attack':43, 'defense':9, 'country':'Germany'}]
我当前的代码:
search_key_list = [key for key in filter_options.keys()]
header_index_list = [header.index(i) for i in search_key_list if i in header]
answer = []
for i in header_index_list:
for d in data:
if type(filter_options[header[i]]) == int or type(filter_options[header[i]]) == float:
if data[header[i]]>filter_options[header[i]]:
answer.append(d)
elif type((filter_options[header[i]])) == str:
if data[header[i]] == filter_options[header[i]]:
answer.append(d)
代码是错误的,因为它没有考虑多个标准。它正在查看一个标准,检查哪个子列表符合标准,将子列表附加到答案列表,然后继续下一个标准。
我该如何纠正这个问题?或者还有哪些其他代码可以使用?
【问题讨论】:
标签: python python-2.7 list dictionary filter