我創建了一個不為空的字典(dict1),其中包含具有相應串列的鍵作為它們的值。我想創建一個新字典(dict2),其中應將由某些標準修改的新串列存盤為具有原始字典中相應鍵的值。但是,當嘗試在每個回圈期間迭代地將新創建的串列( list1 )添加到字典( dict2)時,存盤的值是空串列。
dict1 = {"key1" : [-0.04819, 0.07311, -0.09809, 0.14818, 0.19835],
"key2" : [0.039984, 0.0492105, 0.059342, -0.0703545, -0.082233],
"key3" : [0.779843, 0.791255, 0.802576, 0.813777, 0.823134]}
dict2 = {}
list1 = []
for key in dict1:
if (index 1 < len(dict1[key]) and index - 1 >= 0):
for index, element in enumerate(dict1[key]):
if element - dict1[key][index 1] > 0:
list1.append(element)
dict2['{}'.format(key)] = list1
list.clear()
print(dict2)
我想要的輸出:
dict2 = {"key1" : [0.07311, 0.14818, 0.19835],
"key2" : [0.039984, 0.0492105, 0.059342],
"key3" : [0.779843, 0.791255, 0.802576, 0.813777, 0.823134]}
uj5u.com熱心網友回復:
問題是它list總是參考同一個串列,你可以通過呼叫clear. 因此 dict 中的所有值都參考記憶體中相同的空串列物件。
>>> # ... running your example ...
>>> [id(v) for v in dict2.values()]
[2111145975936, 2111145975936, 2111145975936]
看起來您想從dict1. 一個簡單的 dict-comprehension 就可以完成這項作業。
>>> dict2 = {k: [x for x in v if x > 0] for k, v in dict1.items()}
>>> dict2
{'key1': [0.07311, 0.14818, 0.19835],
'key2': [0.039984, 0.0492105, 0.059342],
'key3': [0.779843, 0.791255, 0.802576, 0.813777, 0.823134]}
uj5u.com熱心網友回復:
@timgeb 提供了一個很好的解決方案,可以將您的代碼簡化為字典理解,但沒有顯示如何修復現有代碼。正如他在那里所說,您在 for 回圈的每次迭代中都重用了相同的串列。因此,要修復您的代碼,您只需要在每次迭代時創建一個新串列即可:
for key in dict1:
my_list = []
# the rest of the code is the same, expect you don't need to call clear()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439282.html
上一篇:使用兩個條件重新排列子字串
