迭代地将新列表作为值添加到字典中
我创建了一个字典(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]}
I have created a dictionary (dict1) which is not empty and contains keys with corresponding lists as their values. I want to create a new dictionary (dict2) in which new lists modified by some criterion should be stored as values with the corresponding keys from the original dictionary. However, when trying to add the newly created list (list1) during every loop iteratively to the dictionary (dict2) the stored values are empty lists.
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)
The output I want:
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]}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是
list
始终引用同一个列表,您可以通过调用clear
清空该列表。因此,字典中的所有值都引用内存中的同一个空列表对象。看起来您想从
dict1
中的值中过滤掉负元素。一个简单的听写理解就可以完成这项工作。The problem is that
list
always refers to the same list, which you empty by callingclear
. Therefore all values in the dict refer to the same empty list object in memory.It looks like you want to filter out negative elements from the values in
dict1
. A simple dict-comprehension will do the job.@timgeb 提供了一个很好的解决方案,它将您的代码简化为字典理解,但没有显示如何修复现有代码。正如他所说,您在 for 循环的每次迭代中重复使用相同的列表。因此,要修复代码,您只需在每次迭代中创建一个新列表:
@timgeb gives a great solution which simplifies your code to a dictionary comprehension but doesn't show how to fix your existing code. As he says there, you are reusing the same list on each iteration of the for loop. So to fix your code, you just need to create a new list on each iteration instead: