例如,当我执行frozen = frozenset(('kay', 'snow queen'))
,然后执行tuple(frozen)
时,我得到('kay', 'snow queen')
。 ({/ 1}}(何时/如何)是否有可能iter(frozen)
以不同顺序生产商品? (何时/如何)tuple(frozen)
返回('snow queen', 'kay')
?
我几乎一直都在使用Python 3,但是我也会对Python 2感到好奇。
答案 0 :(得分:3)
默认情况下,str
个对象的哈希值带有不可预测的随机值。尽管它们在单个Python进程中保持不变,但是在重复调用Python之间是不可预测的。更改哈希值会影响集合的迭代顺序。
因此,启用散列随机化后,您将获得不同顺序的项目:
$ 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']
如果您disable it,将获得可重复但任意的顺序:
$ 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开始,哈希随机化默认情况下启用为workaround a security vulnerability。