Find object by its member inside a List in python

后端 未结 4 1573
执笔经年
执笔经年 2021-02-02 11:21

lets assume the following simple Object:

class Mock:
    def __init__(self, name, age):
        self.name = name
        self.age = age

then I

4条回答
  •  天涯浪人
    2021-02-02 11:52

    You might want to pre-index them -

    from collections import defaultdict
    
    class Mock(object):
        age_index = defaultdict(list)
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
            Mock.age_index[age].append(self)
    
        @classmethod
        def find_by_age(cls, age):
            return Mock.age_index[age]
    

    Edit: a picture is worth a thousand words:

    enter image description here

    X axis is number of Mocks in myList, Y axis is runtime in seconds.

    • red dots are @dcrooney's filter() method
    • blue dots are @marshall.ward's list comprehension
    • green dots hiding behind the X axis are my index ;-)

提交回复
热议问题