亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從兩個單獨的列表中創建一個每個鍵具有多個值的字典?

如何從兩個單獨的列表中創建一個每個鍵具有多個值的字典?

滄海一幻覺 2022-04-27 14:07:04
我正在嘗試創建一個每個鍵具有多個值的字典。例如: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']我想創建一個看起來像這樣的字典:{'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'], 'Renault': ['Reanault_Twingo']}使用我嘗試過的代碼,每個品牌只能獲得一個型號,并且找不到添加不在 common_brands 列表中的品牌的方法。models_by_brand = {}for brand in common_brands:    for model in top_10:        if brand in model.lower():            models_by_brand[brand] = [model]models_by_brand輸出:{'bmw': ['BMW_320i'], 'ford': ['Ford_Fiesta'], 'opel': ['Opel_Corsa_1.2_16V'], 'volkswagen': ['Volkswagen_Golf']}
查看完整描述

3 回答

?
慕俠2389804

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字典中當前沒有模型,將創建并使用一個空列表。


查看完整回答
反對 回復 2022-04-27
?
Helenr

TA貢獻1780條經驗 獲得超4個贊

# 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)


查看完整回答
反對 回復 2022-04-27
?
慕無忌1623718

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 的答案將是最有效的答案。


查看完整回答
反對 回復 2022-04-27
  • 3 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號