簡體   English   中英

迭代地將新列表作為值添加到字典中

[英]Iteratively adding new lists as values to a dictionary

我創建了一個字典 ( 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)

我要的output:

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]}

問題是list總是引用同一個列表,您可以通過調用clear清空該列表。 因此,字典中的所有值都引用 memory 中的同一個空列表 object。

>>> # ... running your example ...
>>> [id(v) for v in dict2.values()]
[2111145975936, 2111145975936, 2111145975936]

看起來您想從dict1的值中過濾掉負元素。 一個簡單的字典理解就可以完成這項工作。

>>> 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]}

@timgeb 提供了一個很好的解決方案,可以將您的代碼簡化為字典理解,但不會顯示如何修復現有代碼。 正如他在那里所說,您在 for 循環的每次迭代中重復使用相同的列表。 因此,要修復您的代碼,您只需要在每次迭代時創建一個新列表:

for key in dict1:
    my_list = []
    # the rest of the code is the same, expect you don't need to call clear()

暫無
暫無

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

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