Find object by its member inside a List in python

后端 未结 4 1575
执笔经年
执笔经年 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)]
    

提交回复
热议问题