List comprehension vs. lambda + filter

前端 未结 14 2142
挽巷
挽巷 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 03:04

    An important difference is that list comprehension will return a list while the filter returns a filter, which you cannot manipulate like a list (ie: call len on it, which does not work with the return of filter).

    My own self-learning brought me to some similar issue.

    That being said, if there is a way to have the resulting list from a filter, a bit like you would do in .NET when you do lst.Where(i => i.something()).ToList(), I am curious to know it.

    EDIT: This is the case for Python 3, not 2 (see discussion in comments).

提交回复
热议问题