gpt4 book ai didi

python - python中的字典顺序

转载 作者:太空狗 更新时间:2023-10-30 00:31:38 24 4
gpt4 key购买 nike

无论我在哪里搜索,他们都说 python 字典没有任何顺序。当我每次运行代码 1 时都会显示不同的输出(随机顺序)。但是当我运行代码 2 时,它总是显示相同的排序输出。为什么字典在第二个片段中排序?

   #code 1

d = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
for a, b in d.items():
print(a, b)
#code 2

d = {1: 10, 2: 20, 3: 30, 4: 40}
for a, b in d.items():
print(a, b)

输出

代码 1:

four 4
two 2
three 3
one 1

再次编码 1:

three 3
one 1
two 2
four 4

代码 2(始终):

1 10
2 20
3 30
4 40

最佳答案

这与哈希随机化的应用方式有关。引用 docs (强调我的):

By default, the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.

对于后续的每次运行,您的字符串(片段 1 中的键)都使用不同的加盐值进行哈希处理 - 因此哈希值也会发生变化。哈希值决定顺序。

对于 int 类型,散列函数永远不会改变 - 事实上散列总是等于整数值。

assert hash(42) == 42

如果哈希函数永远不会改变,则后续运行中的顺序也不会改变。

Python字典的具体实现方式可以引用How are Python's Built In Dictionaries Implemented .

关于python - python中的字典顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34499794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com