python - 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
我有两个问题:
tuple() 的预期行为是什么:
1.1 生成有序元组?
1.2 修改输入?
我在哪里可以找到最终的文档?我检查了 Python 在线文档https://docs.python.org/3/library/stdtypes.html#tuple,它根本没有提供这样的信息。
谢谢。
解决方案
一个集合是无序的,而一个列表是有序的。因此tuple(a_list)
保留列表的顺序,但tuple(a_set)
没有明确的顺序可遵循。
推荐阅读
- excel - 如何在 Excel 宏中指定范围以根据列中的数据将表格导出到多个 CSV 文件
- linux-kernel - 我可以在不从引导加载程序传递单独的 DTB 的情况下引导 linux 内核吗?
- django - Django - 我如何让 id 转到下一个可用的号码?(在应用程序之外添加记录)
- oracle - Oracle PLSQL 编码——UTF-8 到 UTF-BOM 的转换
- django - 与用户模型的关系(django)
- pandas - 是否可以在 Pandas 中使用 iterrows 选择多行?
- oracle - 为什么长度(列)和长度b(列)返回相同的长度?
- c - C/C++ 运行时检查失败 #2 - 变量“gradeLetter”周围的堆栈已损坏。Visual Studio 2019。如何解决这个问题?
- heroku - 将 g++ 添加到 heroku 节点服务器
- java - 即使 Activity 被销毁,Android Handler 也会继续运行一段时间