Searching a list of objects in Python

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

    You should add a __eq__ and a __hash__ method to your Data class, it could check if the __dict__ attributes are equal (same properties) and then if their values are equal, too.

    If you did that, you can use

    test = Data()
    test.n = 5
    
    found = test in myList
    

    The in keyword checks if test is in myList.

    If you only want to a a n property in Data you could use:

    class Data(object):
        __slots__ = ['n']
        def __init__(self, n):
            self.n = n
        def __eq__(self, other):
            if not isinstance(other, Data):
                return False
            if self.n != other.n:
                return False
            return True
        def __hash__(self):
            return self.n
    
        myList = [ Data(1), Data(2), Data(3) ]
        Data(2) in myList  #==> True
        Data(5) in myList  #==> False
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-02 07:55

    Just for completeness, let's not forget the Simplest Thing That Could Possibly Work:

    for i in list:
      if i.n == 5:
         # do something with it
         print "YAY! Found one!"
    
    0 讨论(0)
  • 2020-12-02 07:59

    Consider using a dictionary:

    myDict = {}
    
    for i in range(20):
        myDict[i] = i * i
    
    print(5 in myDict)
    
    0 讨论(0)
  • 2020-12-02 08:02

    Another way you could do it is using the next() function.

    matched_obj = next(x for x in list if x.n == 10)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题