Skip to main content
 首页 » 编程设计

python之在 Python 中搜索对象列表

2025年05月04日18tintown

我有一个具有日期属性的 Item 对象列表。我还有一个从数据库中获取的日期。

我想搜索列表,找到所有大于我从数据库返回的日期的列表项。

我的 Items 对象列表中有超过一千个对象,因此我希望尽可能高效。

我认为循环遍历列表中的每个项目并检查它是否大于我从数据库返回的日期并不是执行此操作的最有效方法。

class Item(object):     
    def __init__(self, title, link, description, date): 
        self.title = title 
        self.link = link 
        self.description = description 
        self.date = date 
 
item_list = []  
... 
#assume I populate the list with a 1,000 Item objects 
 
filtered_list = [] 
for it in item_list: 
    if date_from_db > it.date: 
        filtered_list.append(it) 

请您参考如下方法:

列表理解是在数据库之外执行此操作的一种相当有效的方法:

[it for it in item_list if date_from_db > it.date] 

否则,您可以使用内置的 filter:

filter(lambda it: it if date_from_db > it.date, item_list)