Find object by its member inside a List in python

后端 未结 4 1567
执笔经年
执笔经年 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:33

    List comprehensions are almost always the faster way to do these things (2x as fast here), though as mentioned earlier indexing is even faster if you're concerned about speed.

    ~$ python -mtimeit -s"from mock import myList" "filter(lambda x: x.age==21, myList)"
    1000000 loops, best of 3: 1.34 usec per loop
    ~$ python -mtimeit -s"from mock import myList" "[x for x in myList if x.age==21]"
    1000000 loops, best of 3: 0.63 usec per loop
    

    For file mock.py in current directory:

    class Mock:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    myList = [Mock('Tom', 20), Mock('Dick', 21), Mock('Harry', 21), Mock('John', 22)]
    
    0 讨论(0)
  • 2021-02-02 11:42

    You could try a filter():

    filter(lambda x: x.age == 30, myList)
    

    This would return a list with only those objects satisfying the lambda expression.

    0 讨论(0)
  • 2021-02-02 11:45

    List comprehensions can pick these up:

    new_list = [x for x in myList if x.age == 30]
    
    0 讨论(0)
  • 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 ;-)
    0 讨论(0)
提交回复
热议问题