Skip to main content
 首页 » 编程设计

python之使用字典过滤对象列表

2024年11月01日10bjzhanghao

假设我有一个这样的数据结构(对象列表):

[ 
 <-- 
    Name: Bob 
    Job: Programmer 
    Location: Salem 
  -->, 
 <-- 
    Name: Steve 
    Job: Sales 
    Location: New York 
 -->, 
 <-- 
    Name: Jeff 
    Job: Programmer 
    Location: New York 
 --> 
] 

现在假设我有一个 Web 表单,它将返回一个字典,其中每个键都将引用对象中的一个字段。例如,假设我像这样取回字典:

{"Name": [""], "Job": ["Programmer"], "Location": ["Salem", "New York"]} 

这是为了返回塞勒姆和纽约位置的所有程序员:Bob 和 Jeff。它将始终是字符串列表的字典。我只想检查对象的字符串值是否包含此字符串。

问题在于遍历字典的每个条目并确保每个对象都匹配字典的所有规范。 这是我当前的代码,它在逻辑上只生成一个对象列表,其中包含包含任何参数的任何对象,这不是我想要的:

return_list = [] 
filter_dictionary = dict(request.form) 
for row in data: 
  for key, value in filter_dictionary.iteritems(): 
    for obj in value: 
      if obj in str(getattr(row, key)): 
        return_list.append(row) 
return return_list 

我敢肯定,一定有一种更聪明、更好的方法来做到这一点,或许可以使用涉及集合的方法。我该怎么做?

返回值最终应该是一个对象列表,就像在原始示例中一样,但只包含满足 filter_dictionary

所有规范的对象

请您参考如下方法:

其他人可能会给出更简洁的解决方案,但我认为最接近您现有代码的调整是这样的:

return_list = [] 
filter_dictionary = dict(request.form) 
for row in data: 
  match = True # we set to False if any attribute doesn't match 
  for key, value in filter_dictionary.items(): 
    attrmatch = False # we need at least one match per attribute 
    for obj in value: 
      if obj in str(getattr(row, key)): attrmatch = True 
    if not attrmatch: match = False 
  if match: return_list.append(row)