3 回答
TA贡献1719条经验 获得超6个赞
您可以使用defaultdict并拆分车辆的名称以获得品牌(如果这些已标准化):
from collections import defaultdict
models_by_brand = defaultdict(list)
for model in top_10:
brand = model.lower().split('_')[0]
models_by_brand[brand].append(model)
通过使用defaultdict,您可以编写models_by_brand[brand].append(model),如果brand字典中当前没有模型,将创建并使用一个空列表。
TA贡献1780条经验 获得超3个赞
# The following code should work just fine.
top_10 = ['Volkswagen_Golf_1.4', 'BMW_316i', 'Ford_Fiesta', 'BMW_318i', 'Volkswagen_Polo', 'BMW_320i', 'Opel_Corsa',
'Renault_Twingo', 'Volkswagen_Golf', 'Opel_Corsa_1.2_16V']
common_brands = ['volkswagen', 'bmw', 'opel', 'mercedes_benz', 'audi', 'ford']
result = {}
cars = []
# For each car brand
for k in common_brands:
# For each car model
for c in top_10:
# if car brand present in car model name append it to list
if k.lower() in c.lower():
cars.append(c)
# if cars list is not empty copy it to the dictionary with key k
if len(cars) > 0:
result[k] = cars.copy()
# Reset cars list for next iteration
cars.clear()
print(result)
TA贡献1744条经验 获得超4个赞
如果要保留代码的结构,请使用列表:
models_by_brand = {}
for brand in common_brands:
model_list=[]
for model in top_10:
if brand in model.lower():
model_list.append(model)
models_by_brand[brand] = model_list
models_by_brand = {k:v for k,v in models_by_brand.items() if v!=[]}
输出:
{'volkswagen': ['Volkswagen_Golf_1.4', 'Volkswagen_Polo', 'Volkswagen_Golf'],
'bmw': ['BMW_316i', 'BMW_318i', 'BMW_320i'],
'opel': ['Opel_Corsa', 'Opel_Corsa_1.2_16V'],
'ford': ['Ford_Fiesta']}
不过,@Holt 的答案将是最有效的答案。
添加回答
举报