首页 > 解决方案 > Python tuple() :它什么时候重新排序?

问题描述

我正在使用 Python 3.7 并且对 tuple() 感到困惑。有时它会重新排序数据,有时不会:

>>> a=tuple([2, 1, 3])
>>> print(a)
(2, 1, 3)   <== the tuple from list is not re-ordered

>>> s={2, 1, 3}
>>> b=tuple(s)
>>> print(b)
(1, 2, 3)   <== the tuple from set is re-ordered

>>> print(tuple({10, 5, 30}))
(10, 5, 30)  <== the tuple from set is not re-ordered

>>> print(s)
{1, 2, 3}    <== the set itself is re-ordered

我有两个问题:

  1. tuple() 的预期行为是什么:

    1.1 生成有序元组?

    1.2 修改输入?

  2. 我在哪里可以找到最终的文档?我检查了 Python 在线文档https://docs.python.org/3/library/stdtypes.html#tuple,它根本没有提供这样的信息。

谢谢。

标签: pythonset

解决方案


一个集合是无序的,而一个列表是有序的。因此tuple(a_list)保留列表的顺序,但tuple(a_set)没有明确的顺序可遵循。


推荐阅读