简体   繁体   English

使用过滤器替换Python中的搜索功能

[英]Using filter to replace search function in Python

To Python lovers and experts,致 Python 爱好者和专家,

My code:我的代码:

def getAssignee(keyTitle):
    assignee = ''
    for item in assigneeList:
        if(item['title']==keyTitle):
            assignee = item['name']
            break
    return assignee

My intention: To try out filter in python and replace above code with filter function.我的意图:在 python 中尝试过滤器用过滤器函数替换上面的代码。 Assignee list is a list of dictionaries.受让人列表是字典列表。 Eg例如

assigneeList = [{'title':'Book', 'name':'Davis'},{'title':'TV','name':'Samsung'}]

My reference: Most efficient way to search in list of dicts我的参考: 在字典列表中搜索的最有效方法

My attempt:我的尝试:

assignee = filter(lambda item: item['title']=='TV',assigneeList)
print(assignee['name'])

My Output: Not working.我的输出:不工作。 Error "Value 'assignee' is unsubscriptable"错误“值‘受让人’不可订阅”

My question: How to get the assignee name, like how I got from the getAssignee() function?我的问题:如何获取受让人名称,就像我从 getAssignee() 函数中获取的一样?

The result of filter is a filter object, you can handle this several ways, and handling the eventuality of an empty filter filter的结果是一个过滤器对象,你可以通过几种方式处理这个,以及处理一个空过滤器的可能性

  • use next(.., None) to get first matching or None value使用next(.., None)获取第一个匹配或None

    def getAssignee(keyTitle): assignee = next(filter(lambda item: item['title'] == keyTitle, assigneeList), None) return assignee['name'] if assignee else ''
  • collect the items in a list then pic the first收集列表中的项目然后图片第一个

    def getAssignee(keyTitle): assignee = list(filter(lambda item: item['title'] == keyTitle, assigneeList)) return assignee[0]['name'] if assignee else ''

The next solution if more performant as it don't generates all the filter object, (the list will consumes all the filter, and eventually it could be big) next解决方案如果性能更高,因为它不生成所有过滤器对象,( list将消耗所有过滤器,最终它可能很大)

>>> assignee = filter(lambda item: item['title']=='TV',assigneeList)
>>> type(assignee)
<class 'filter'>

In python 3 filter function will return filter object.在 python 3 filter函数中将返回过滤器对象。 filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) . filter(function, iterable)等价于生成器表达式(item for item in iterable if function(item)) So In order to evaluate the items you can call list(assignee)因此,为了评估您可以调用list(assignee)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM