简体   繁体   中英

Using filter to replace search function in Python

To Python lovers and experts,

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. 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?

The result of filter is a filter object, you can handle this several ways, and handling the eventuality of an empty filter

  • use next(.., None) to get first matching or None value

    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)

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

In python 3 filter function will return filter object. filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) . So In order to evaluate the items you can call list(assignee)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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