List comprehension vs. lambda + filter

前端 未结 14 2418
挽巷
挽巷 2020-11-22 02:01

I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.

My code looked like this:



        
14条回答
  •  暖寄归人
    2020-11-22 02:59

    In addition to the accepted answer, there is a corner case when you should use filter instead of a list comprehension. If the list is unhashable you cannot directly process it with a list comprehension. A real world example is if you use pyodbc to read results from a database. The fetchAll() results from cursor is an unhashable list. In this situation, to directly manipulating on the returned results, filter should be used:

    cursor.execute("SELECT * FROM TABLE1;")
    data_from_db = cursor.fetchall()
    processed_data = filter(lambda s: 'abc' in s.field1 or s.StartTime >= start_date_time, data_from_db) 
    

    If you use list comprehension here you will get the error:

    TypeError: unhashable type: 'list'

提交回复
热议问题