【发布时间】:2020-05-14 10:53:40
【问题描述】:
我想了解在将新数据添加到字典时,python 中的内存分配是如何工作的。在下面的代码中,我一直在等待每个新添加的数据最后都堆叠起来,但是它没有发生。
repetitions = {}
for item in new_deltas:
list_aux = []
if float(item[1]) <= 30:
if float(item[0]) in repetitions:
aux = repetitions[float(item[0])]
aux.append(item[1])
repetitions[float(item[0])] = aux
else:
list_aux.append(item[1])
repetitions[float(item[0])] = list_aux
print(repetitions)
我得到的结果如下。因此,我想了解为什么新的附加数据没有添加到堆栈的末尾,而是添加到了堆栈的中间。
我的输入数据是:
new_deltas = [[1.452, 3.292182683944702], [1.449, 4.7438647747039795], [1.494, 6.192960977554321], [1.429, 7.686920166015625]]
打印行输出:
{1.452: [3.292182683944702]}
{1.452: [3.292182683944702], 1.449: [4.7438647747039795]}
{1.452: [3.292182683944702], 1.494: [6.192960977554321], 1.449: [4.7438647747039795]}
{1.429: [7.686920166015625], 1.452: [3.292182683944702], 1.494: [6.192960977554321], 1.449: [4.7438647747039795]}
【问题讨论】:
-
repititions.keys()的顺序是什么? - 我无法重现,我得到了你所期望的 - Python 3.6。 -
我使用的是 python 3.5.2。 repeats.keys() 的顺序是:dict_keys([1.429, 1.452, 1.494, 1.449])
-
Python dicts 传统上不保留插入顺序;对它们进行迭代会产生任意顺序。我认为这在 3.6 中发生了变化。
-
@jasonharper 它在 3.6 中更改为 CPython 的实现细节;从 3.7 开始,该语言要求所有实现都这样做。
-
这和内存分配有什么关系?
标签: python python-3.x algorithm dictionary hashtable