是否保证总是在相同的冻结集上进行迭代才能以相同的顺序生产商品? (Python 3) [英] Is iterating over the same frozenset guaranteed always to produce the items in the same order? (Python 3)

查看:102
本文介绍了是否保证总是在相同的冻结集上进行迭代才能以相同的顺序生产商品? (Python 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,当我执行frozen = frozenset(('kay', 'snow queen')),然后执行tuple(frozen)时,我得到('kay', 'snow queen'). (何时/如何)iter(frozen)是否有可能以不同的顺序生产商品? (何时/如何)tuple(frozen)返回('snow queen', 'kay')?

For example, when I execute frozen = frozenset(('kay', 'snow queen')), then tuple(frozen), I get ('kay', 'snow queen'). (When / how) is it possible, if ever, for iter(frozen) to produce the items in a different order? (When / how) will tuple(frozen) return ('snow queen', 'kay')?

我几乎一直都在使用Python 3,但我也对Python 2感到好奇.

I am using Python 3 almost all of the time, but I would also be curious about Python 2.

推荐答案

默认情况下,str对象的哈希值带有不可预测的随机值.尽管它们在单个Python进程中保持不变,但在重复调用Python之间是不可预测的.更改哈希值会影响集合的迭代顺序.

By default, the hash values of str 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. Changing hash values affects the iteration order of sets.

因此,启用散列随机化后,您将获得不同顺序的项目:

So, when hash randomization is on, you will get items in a different order:

$ for i in {1..10}; do python3 -c "frozen = frozenset(('kay', 'snow queen')); print(list(frozen))"; done
['snow queen', 'kay']
['snow queen', 'kay']
['snow queen', 'kay']
['snow queen', 'kay']
['kay', 'snow queen']
['kay', 'snow queen']
['snow queen', 'kay']
['kay', 'snow queen']
['snow queen', 'kay']
['snow queen', 'kay']

如果将其禁用,您将获得一个可重复但任意的顺序:

If you disable it, you will get a repeatable but arbitrary order:

$ export PYTHONHASHSEED=0
$ for i in {1..10}; do python3 -c "frozen = frozenset(('kay', 'snow queen')); print(list(frozen))"; done
['kay', 'snow queen']
['kay', 'snow queen']
['kay', 'snow queen']
['kay', 'snow queen']
['kay', 'snow queen']
['kay', 'snow queen']
['kay', 'snow queen']
['kay', 'snow queen']
['kay', 'snow queen']
['kay', 'snow queen']

从Python 3.3开始,默认情况下,哈希随机化已启用为解决安全漏洞的方法.

Since Python 3.3, hash randomization is enabled by default to workaround a security vulnerability.

另请参见: -R切换到解释器.

See also: the -R switch to the interpreter.

这篇关于是否保证总是在相同的冻结集上进行迭代才能以相同的顺序生产商品? (Python 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆