如何在Python中使用多个条件高效过滤大列表?

问题描述 投票:0回答:1

我正在开发一个Python项目,我需要根据多个条件过滤大量字典。

这是我正在处理的数据结构的简化示例:

data = [
    {"name": "David", "age": 30, "city": "Nairobi"},
    {"name": "Shanice", "age": 25, "city": "Kisumu"},
    {"name": "Shon", "age": 35, "city": "Mombasa"},
    # ... potentially thousands of more entries
]

我想过滤此列表,仅包含年龄大于 28 岁且城市为“内罗毕”或“蒙巴萨”的条目。我当前的方法是使用这样的列表理解:

filtered_data = [
    entry for entry in data
    where entry['age'] > 28 and entry['city'] in ('Nairobi', 'Mombasa')
]

虽然这适用于较小的列表,但对于较大的数据集,性能会成为问题。是否有更有效的方法来执行此过滤,特别是对于非常大的列表?

任何优化此类操作的建议或最佳实践将不胜感激!

python performance filtering list-comprehension
1个回答
0
投票

当然,总是可以选择使用具有强大查询支持和索引的适当数据库,但除此之外,如果您想用现有的东西做一些简单的事情,并且这些类型的搜索是您要做的更多事情一次或两次,然后我会将列表重新调整为适合您搜索的内容。

def build_search(data):
    lookup = {}
    for row in data:
        lookup.setdefault(row["city"], []).append(row)
    return lambda city, age: [row for row in lookup.get(city, []) if row["age"] > age]

data = [
    {"name": "David", "age": 30, "city": "Nairobi"},
    {"name": "Shanice", "age": 25, "city": "Kisumu"},
    {"name": "Shon", "age": 35, "city": "Mombasa"},
    # ... potentially thousands of more entries
]
search =  build_search(data)

print(search("Nairobi", 22))
print(search("Cairo", 22))

应该给你:

[{'name': 'David', 'age': 30, 'city': 'Nairobi'}]
[]
© www.soinside.com 2019 - 2024. All rights reserved.