筛选目录列表以获得最低优先级

2024-05-15 09:32:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的函数,可以根据“Price”和“Stock”从列表中删除“半重复”字典(只保留其中一个字典)。我现在的代码得到的是库存商品的最低价格,但是我想改进一下,如果所有的“半复制”都缺货了,就得到最低价格的商品(库存商品的优先权总是在更高的价格,否则缺货商品的最低价格)

my_list=[{"Product Name":"x","Merchant_1_Price":"33","Merchant_1_Stock":True,"Seller":"y"},
{"Product Name":"x","Merchant_1_Price":"25","Merchant_1_Stock":False,"Seller":"y1"},
{"Product Name":"x","Merchant_1_Price":"32","Merchant_1_Stock":True,"Seller":"y1"},
{"Product Name":"x","Merchant_1_Price":"42","Merchant_1_Stock":True,"Seller":"y2"},
{"Product Name":"x1","Merchant_1_Price":"100","Merchant_1_Stock":True,"Seller":"z1"},...
]
by_asin = {}
for item in my_list:
    if item['Merchant_1_Stock'] == False:
        continue
    asin = item['Product Name']
    if (
        asin not in by_asin or
        float(item['Merchant_1_Price']) < float(by_asin[asin]['Merchant_1_Price'])
    ):
        by_asin[asin] = item
deduplicated_list_of_dicts = list(by_asin.values())

Tags: nametrueby字典stockmerchant价格product
1条回答
网友
1楼 · 发布于 2024-05-15 09:32:55

你可以在这里使用min(..)。作为键,您使用2元组:首先是Merchant_1_Stock的否定,然后是Merchant_1_Price,如:

min(my_list, key=lambda e: (not e['Merchant_1_Stock'], float(e['Merchant_1_Price'])))

对于给定的样本数据,结果是:

>>> min(my_list, key=lambda e: (not e['Merchant_1_Stock'], float(e['Merchant_1_Price'])))
{'Product Name': 'x', 'Merchant_1_Price': '32', 'Merchant_1_Stock': True, 'Seller': 'y1'}

Python按字典顺序对元组排序。这意味着它考虑给定的x1< y1;或x2≤ y2。你知道吗

因为FalseTrue小,这意味着我们把ee['Merchant_1_Stock']的项在这里看作TrueFalse小。如果多个项目的e['Merchant_1_Stock']True,我们将按e['Merchant_1_Price']排序。你知道吗

例如,您可以使用此逻辑来获取每个项目的最便宜价格。我们可以首先使用defaultdict对每个项目进行分组,然后获得最小值。比如:

from collections import defaultdict

products = defaultdict(list)
for item in my_list:
    products[item['Product Name']].append(item)

result = {
    k: min(vs, key=lambda e: (not e['Merchant_1_Stock'], float(e['Merchant_1_Price'])))
    for k, vs in products.items()
}
list(result.values())

这将产生:

>>> {
...     k: min(vs, key=lambda e: (not e['Merchant_1_Stock'], float(e['Merchant_1_Price'])))
...     for k, vs in products.items()
... }
{'x': {'Product Name': 'x', 'Merchant_1_Price': '32', 'Merchant_1_Stock': True, 'Seller': 'y1'}, 'x1': {'Product Name': 'x1', 'Merchant_1_Price': '100', 'Merchant_1_Stock': True, 'Seller': 'z1'}}

或者对于值:

>>> list(result.values())
[{'Product Name': 'x', 'Merchant_1_Price': '32', 'Merchant_1_Stock': True, 'Seller': 'y1'}, {'Product Name': 'x1', 'Merchant_1_Price': '100', 'Merchant_1_Stock': True, 'Seller': 'z1'}]

相关问题 更多 >