Searching a list of objects in Python

后端 未结 9 1406
滥情空心
滥情空心 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:06

    You can get a list of all matching elements with a list comprehension:

    [x for x in myList if x.n == 30]  # list of all elements with .n==30
    

    If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do

    def contains(list, filter):
        for x in list:
            if filter(x):
                return True
        return False
    
    if contains(myList, lambda x: x.n == 3)  # True if any element has .n==3
        # do stuff
    

提交回复
热议问题