Python3 - iter 内置方法是否尽可能对集合元素进行排序?

问题描述 投票:0回答:1

iter 方法从无序集合生成有序集合,如下所示。这个排序结果是 Python 3 的保证行为吗?

x = {1, 9, 2, 8, 4, 6}
y = iter(x)
list(y)
-----
[1, 2, 4, 6, 8, 9]      # <--- Sorted
python-3.x iterator
1个回答
0
投票

不。关于集合的迭代顺序没有任何定义(无论是通过

iter(set)
for e in set:
或...)。

在一组字符串上尝试,您可能会发现顺序在运行过程中发生变化。

您所看到的是

hash(int)
如何计算的间接结果,以及它与今天在CPython下如何实现集合的迭代。

在最近的PyPy下,情况有所不同:

Python 3.10.12 (af44d0b8114cb82c40a07bb9ee9c1ca8a1b3688c, Jun 15 2023, 15:42:22)
[PyPy 7.3.12 with MSC v.1929 64 bit (AMD64)] on win32
...
>>>> x = {1, 9, 2, 8, 4, 6}
>>>> y = iter(x)
>>>> list(y)
[1, 9, 2, 8, 4, 6]

所以原来的订单恰好被保留 - 这也不能保证。

© www.soinside.com 2019 - 2024. All rights reserved.