Searching a list of objects in Python

后端 未结 9 1317
滥情空心
滥情空心 2020-12-02 07:42

Let\'s assume I\'m creating a simple class to work similar to a C-style struct, to just hold data elements. I\'m trying to figure out how to search a list of objects for ob

相关标签:
9条回答
  • 2020-12-02 08:08
    filter(lambda x: x.n == 5, myList)
    
    0 讨论(0)
  • 2020-12-02 08:09

    You can use in to look for an item in a collection, and a list comprehension to extract the field you are interested in. This (works for lists, sets, tuples, and anything that defines __contains__ or __getitem__).

    if 5 in [data.n for data in myList]:
        print "Found it"
    

    See also:

    • Contains Method
    • In operation
    0 讨论(0)
  • 2020-12-02 08:16
    [x for x in myList if x.n == 30]               # list of all matches
    [x.n_squared for x in myList if x.n == 30]     # property of matches
    any(x.n == 30 for x in myList)                 # if there is any matches
    [i for i,x in enumerate(myList) if x.n == 30]  # indices of all matches
    
    def first(iterable, default=None):
      for item in iterable:
        return item
      return default
    
    first(x for x in myList if x.n == 30)          # the first match, if any
    
    0 讨论(0)
提交回复
热议问题