python从字典中选择指定项

2024-03-28 18:50:29 发布

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

假设我有一个汽车清单:

car=[{'model':'ferrari', 'color': 'red', 'price':1200},
{'model':'lamborgini', 'color': 'blue', 'price':2000},
{'model':'ferrari', 'color': 'yellow', 'price':1000},
{'model':'ferrari', 'color': 'yellow', 'price':500}]

我想选择最便宜的汽车为每一个模型的颜色组合(最便宜的红色兰博基尼,最便宜的绿色法拉利等),并把他们在新的名单。你知道吗

输出应为:

[{'model':'ferrari', 'color': 'red', 'price':1200},
{'model':'lamborgini', 'color': 'blue', 'price':2000},
{'model':'ferrari', 'color': 'yellow', 'price':500}]

我该怎么做?你知道吗


Tags: 模型model颜色blueredcarprice汽车
3条回答

创建助手数据结构可能是个好主意。
在这里,我使用一个元组(model,color)作为键的字典

>>> car = [ {'model':'ferrari', 'color': 'red', 'price':1200},
... {'model':'lamborgini', 'color': 'blue', 'price':2000},
... {'model':'ferrari', 'color': 'yellow', 'price':1000},
... {'model':'ferrari', 'color': 'yellow', 'price':500} ]
>>> from operator import itemgetter
>>> from collections import defaultdict
>>> D = defaultdict(list)
>>> for item in car:
...     D[item['model'], item['color']].append(item)
... 
>>> min(D['ferrari', 'yellow'], key=itemgetter('price'))
{'color': 'yellow', 'model': 'ferrari', 'price': 500}

这意味着您不需要每次进行查询时都扫描整个集合

排序和筛选:

 # keep models together and sort by lowest price
srt = sorted(cars, key=lambda x: (x["model"], x["price"]))

# add cheapest of first model in the list
final = [srt[0]]

for d in srt[1:]:
    if final[-1]["color"] != d["color"]:
        final.append(d)
print final
[{'color': 'yellow', 'model': 'ferrari', 'price': 500}, {'color': 'red', 'model': 'ferrari', 'price': 1200}, {'color': 'blue', 'model': 'lamborgini', 'price': 2000}]

我就是这么做的:

car = [ {'model':'ferrari', 'color': 'red', 'price':1200},
{'model':'lamborgini', 'color': 'blue', 'price':2000},
{'model':'ferrari', 'color': 'yellow', 'price':1000},
{'model':'ferrari', 'color': 'yellow', 'price':500} ]

newcar = []

for c in car:
    new = True
    for n in newcar:
        if c['model']==n['model']:
            if c['color']==n['color']:
                if c['price'] < n['price']:
                    n['price'] = c['price']
                    new = False
    if new:
        newcar.append(c)

newcar变量将存储最便宜的。我用你的箱子测试了一下,效果很好。你知道吗

相关问题 更多 >