簡體   English   中英

Python:具有相同值(可變類型)的多個鍵。 更改這些值之一也會更新其他值。 如何避免這種情況?

[英]Python: Multiple keys with same values (mutable type). Changing one of these values updates the other values too. How do I avoid this?

incident_data_dict = {}
for cause in causes_dict:
    if driver in incident_data_dict or vehicle in incident_data_dict:
        incident_data_dict[driver][cause] += causes_dict[cause]
        incident_data_dict[vehicle][cause] += causes_dict[cause]
    else:
        incident_data_dict.update({driver: causes_dict})
        incident_data_dict.update({vehicle: causes_dict})

event_data_dict = {u'Vehicle_1':{'Over Speeding':0,'Over Acceleration':2,'Hard Braking':0},u'Driver_1':{'Over Speeding':0,'Over Acceleration':2 ,'Hard Braking':0}}

參考圖

u'Vehicle_1' (103072304) = {dict} {'超速':0,'超加速':2,2,'硬制動':0}'硬制動' (107104320) = {int} 0'超加速' ( 107104360) = {int} 2個“超速行駛” (107104680) = {int} 0

u'Driver_1' (103088424) = {dict} {'超速':0,'超加速':2,2,'硬制動':0}'硬制動' (107104320) = {int} 0'超加速' ( 107104360) = {int} 2個“超速行駛” (107104680) = {int} 0

像這樣更新event_data_dict [driver]:event_data_dict [driver] [cause] + = Causes_dict [cause]也更新了event_data_dict [vehicle]中的“ cause”鍵,這是因為所有“ cause”鍵都有相同的引用。 這會使這些鍵增加兩次,而不是一次。 我該如何克服呢?

您可以對字典進行深度復制

import copy
incident_data_dict2=copy.deepcopy(incident_data_dict)
#both dictionaries are independent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM