Searching a list of objects in Python

后端 未结 9 1440
滥情空心
滥情空心 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条回答
  •  旧时难觅i
    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

提交回复
热议问题