我正在嘗試構建一個回圈,該回圈遍歷包含串列的字典字典。
對于主字典(dict_all)中的每個子字典,我想遍歷所有串列,以便將串列的第一個元素(僅列“時間”)減去相應串列的每個元素。為了給出一些背景關系,嵌套字典的結構如下所示:
dict_all = { 'dict_20' : {"P1S1": df_list_20[0], "P2S1": df_list_20[1], "P3S1": df_list_20[2], "P4S1": df_list_20[3],
"P5S1": df_list_20[4], "P6S1": df_list_20[5], "P7S1": df_list_20[6], "P8S1": df_list_20[7],
"P9S1": df_list_20[8], "P10S1": df_list_20[9], "P1S2": df_list_20[10], "P2S2": df_list_20[11],
"P3S2": df_list_20[12], "P4S2": df_list_20[13], "P5S2": df_list_20[14], "P6S2": df_list_20[15],
"P7S2": df_list_20[16], "P8S2": df_list_20[17], "P9S2": df_list_20[18], "P10S2": df_list_20[19]},
'dict_40' : {"P1S1": df_list_40[0], "P2S1": df_list_40[1], "P3S1": df_list_40[2], "P4S1": df_list_40[3],
"P5S1": df_list_40[4], "P6S1": df_list_40[5], "P7S1": df_list_40[6], "P8S1": df_list_40[7],
"P9S1": df_list_40[8], "P10S1": df_list_40[9], "P1S2": df_list_40[10], "P2S2": df_list_40[11],
"P3S2": df_list_40[12], "P4S2": df_list_40[13], "P5S2": df_list_40[14], "P6S2": df_list_40[15],
"P7S2": df_list_40[16], "P8S2": df_list_40[17], "P9S2": df_list_40[18], "P10S2": df_list_40[19]}}
(為了舉例,我只拿了兩個嵌套字典,但我總共有六個)
這是二級字典中串列的外觀示例(每個串列的長度不同):
time velocity
0 10.755616 0.059656
1 10.776415 0.131182
2 10.796519 0.232206
3 10.816632 0.355268
4 10.836832 0.531719
5 10.857092 0.751184
6 10.877205 0.964944
7 10.897274 1.136908
8 10.917387 1.333836
9 10.937439 1.553230
10 10.957535 1.726184
11 10.977587 1.870065
12 10.997622 2.049414
13 11.017821 2.211132
14 11.037908 2.248697
15 11.057977 2.261453
16 11.078099 2.244839
17 11.098168 2.116589
18 11.118351 1.981216
19 11.138455 1.774250
20 11.158568 1.499906
21 11.178724 1.250161
22 11.198863 1.002039
23 11.219028 0.751948
24 11.239314 0.486585
25 11.259696 0.264919
回圈的全部目的是針對每個串列,使“時間”列從“0”開始,同時保持每行之間的時間間隔相同。
I managed to code the following loop that iterate over an isolated list, and that give me the desired output:
for i in range(len(dfList_20[0]['time'])):
dfList_20[0]['time'][:] = dfList_20[0]['time'][:] - dfList_20[0]['time'][0]
But of course it would not be very efficient to iterate at the level of the lists, as it would take me 240 lines of code to fully reach the desired output ..
Thank you all in advance for your time and your solutions ! :)
uj5u.com熱心網友回復:
使用嵌套回圈
for nested_dict in dict_all.values():
for dflist in nested_dict.values():
dflist['time'][:] = dflist['time'][:] - dflist['time'][0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/441365.html
標籤:python loops dictionary for-loop nested
下一篇:使用串列遍歷字典
