簡體   English   中英

如何避免使用for循環將列表中的數據覆蓋到字典中?

[英]How to avoid overwriting the data from a list to a dictionary using for loop?

我有一個嵌套字典如下:

bus = dict()
pvsystem = dict()
    for j in range(500):
        bus[j] = {'vm': {'a': 1, 'b': 1, 'c': 1}, 'va': {'a': 1, 'b': 1, 'c': 1}}
    nw = dict()
    for step in range(24):
        c = step + 1
        nw[str(c)] = {'bus': bus}
    solution = {'nw': nw}
    results = {'solution': solution}

我正在使用 for 循環來填充嵌套字典中的值,如下所示:

for step in range(10):
    c = step + 1
    for b in range(20):
        AllpuVmVa = dss.Bus.puVmagAngle()
        results['solution']['nw'][str(c)]['bus'][b]["vm"]['a'] = AllpuVmVa[0]
        results['solution']['nw'][str(c)]['bus'][b]["va"]['a'] = AllpuVmVa[1]
    print("Step: ", c, " Voltages: ", AllpuVmVa)

AllpuVmVa是一個列表。 一旦步驟改變,它的值就會改變(它是基於循環外的函數定義的)。

這里,使用print函數,很明顯AllpuVmVa在每一步的值都不一樣,但是存儲在( results['solution']['nw'][str(c)]['bus'][b]["vm"]['a'] ) 和 ( results['solution']['nw'][str(c)]['bus'][b]["va"]['a'] ) 對所有步驟都相同,即等於最后一步。 聽起來數據被覆蓋了。

有什么想法可以解決這個問題嗎?

問題是,您將存儲在bus的相同字典分配給nw dict 中的每個值。 為了解決這個問題,你可以在每次迭代時制作新的bus字典。 例如:

bus = dict()
pvsystem = dict()

def get_bus():
    return {j: {'vm': {'a': 1, 'b': 1, 'c': 1}, 'va': {'a': 1, 'b': 1, 'c': 1}} for j in range(500)}

nw = dict()
for step in range(24):
    c = step + 1
    nw[str(c)] = {'bus': get_bus()}     # <-- use get_bus() here

solution = {'nw': nw}
results = {'solution': solution}

暫無
暫無

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

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