Skip to main content
 首页 » 编程设计

python之如何使用 python lambdas 或列表理解根据条件获取列表的子集

2024年10月17日7lonelyxmas

我有一个这样的字典列表。

somelist = [ 
    { "store" : Amazon, "price": 1000}, 
    { "store" : Junglee, "price": 1200}, 
    { "store" : BestBuy, "price": 1300}, 
    { "store" : Amazon, "price": 900}, 
    { "store" : BestBuy, "price": 1200} 
] 

我想对其进行过滤,以便只获取那些具有独特商店且价格最低的词典。所以最后的结果应该是

[ 
    { "store" : Amazon, "price": 900}, 
    { "store" : Junglee, "price": 1200}, 
    { "store" : BestBuy, "price": 1200} 
] 

在 python 中最好的方法是什么?

请您参考如下方法:

你可以收集字典到OrderedDict其中 key 是商店,value 是最低价格。然后你可以很容易地用列表理解重建字典:

from collections import OrderedDict 
 
d = OrderedDict() 
for x in somelist: 
    d[x['store']] = min(d.get(x['store'], float('inf')), x['price']) 
 
[{'store': k, 'price': v} for k, v in d.items()] # [{'price': 900, 'store': 'Amazon'}, {'price': 1200, 'store': 'Junglee'}, {'price': 1200, 'store': 'BestBuy'}] 

如果不需要保留商店的顺序,您也可以使用标准的 dict。