Searching a list of objects in Python

后端 未结 9 1394
滥情空心
滥情空心 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 07:54

    Simple, Elegant, and Powerful:

    A generator expression in conjuction with a builtin… (python 2.5+)

    any(x for x in mylist if x.n == 10)
    

    Uses the Python any() builtin, which is defined as follows:

    any(iterable) -> Return True if any element of the iterable is true. Equivalent to:

    def any(iterable):
        for element in iterable:
            if element:
                return True
        return False
    

提交回复
热议问题