相关疑难解决方法(0)

Python frozenset哈希算法/实现

我目前正在尝试理解为Python的内置frozenset数据类型定义的哈希函数背后的机制.实施情况显示在底部以供参考.我特别感兴趣的是选择这种散射操作的基本原理:

lambda h: (h ^ (h << 16) ^ 89869747) * 3644798167
Run Code Online (Sandbox Code Playgroud)

h每个元素的哈希值在哪里.有谁知道这些来自哪里?(也就是说,有没有特别的理由选择这些数字?)或者他们只是随意选择?


这是官方CPython实现的片段,

static Py_hash_t
frozenset_hash(PyObject *self)
{
    PySetObject *so = (PySetObject *)self;
    Py_uhash_t h, hash = 1927868237UL;
    setentry *entry;
    Py_ssize_t pos = 0;

    if (so->hash != -1)
        return so->hash;

    hash *= (Py_uhash_t)PySet_GET_SIZE(self) + 1;
    while (set_next(so, &pos, &entry)) {
        /* Work to increase the bit dispersion for closely spaced hash
           values.  The is important because some use cases have many
           combinations of a small number …
Run Code Online (Sandbox Code Playgroud)

python hash set

21
推荐指数
2
解决办法
3295
查看次数

在python中列出一个可以使用的ints列表

我有一个整数列表,我想用作python词典中的键.我正在缓存一个以int的列表作为输入的函数的结果.我目前的解决方案

list_of_ints = [1,20,3,4]
key = str(sorted(list_of_ints))[1:-1].replace(' ','')
Run Code Online (Sandbox Code Playgroud)

它产生关键'1,3,4,20'.似乎应该有更快/更漂亮/更pythonic的方式来做到这一点.

python hash

1
推荐指数
2
解决办法
5470
查看次数

标签 统计

hash ×2

python ×2

set ×1