我们说我有汽车清单:
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}]
我想为每种型号颜色组合(最便宜的红色lamborgini,最便宜的绿色法拉利等)选择最便宜的汽车,并将它们列入新的列表。
输出应为:
[{'model':'ferrari', 'color': 'red', 'price':1200},
{'model':'lamborgini', 'color': 'blue', 'price':2000},
{'model':'ferrari', 'color': 'yellow', 'price':500}]
我该怎么做?
答案 0 :(得分:1)
创建辅助数据结构可能是个好主意 在这里,我使用一个字典,其中包含(模型,颜色)元组作为键
>>> 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}
这意味着您每次进行查询时都不需要扫描整个集合
答案 1 :(得分:0)
这就是我所做的:
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
变量将存储最便宜的变量。我用你的情况对它进行了测试,结果很好。
答案 2 :(得分:0)
排序和过滤:
# 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}]
答案 3 :(得分:-1)
cars = [ {'model':'ferrari', 'color': 'red', 'price':1200},
{'model':'lamborgini', 'color': 'blue', 'price':2000},
{'model':'ferrari', 'color': 'yellow', 'price':1000},
{'model':'ferrari', 'color': 'yellow', 'price':500} ]
uniques = {}
for car in cars:
if car['model'] not in uniques:
uniques[car['model']] = {}
if car['color'] not in uniques[car['model']]:
uniques[car['model']][car['color']] = float('inf')
if car['price'] < uniques[car['model']][car['color']]:
uniques[car['model']][car['color']] = car['price']
print(uniques)
输出:
{'ferrari': {'yellow': 500, 'red': 1200}, 'lamborgini': {'blue': 2000}}