python - 必须使用元组的情况

标签 python list tuples

在 Python 中,我所知道的列表和元组之间的唯一区别是“列表是可变的,但元组不是”。但据我所知,这取决于编码人员是否愿意冒可变性的风险。

所以我想知道是否存在必须在列表上使用元组的情况。用列表做不到但用元组可以做的事情?

最佳答案

您可以将元组用作字典中的键并将元组插入集合中:

>>> {}[tuple()] = 1
>>> {}[list()] = 1 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

这基本上是 tuple 是可散列的,而 list 不是:

>>> hash(list())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(tuple())
3527539

关于python - 必须使用元组的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11399026/

相关文章:

python - Pandas :在数据框中重新分配值

python - PyCharm 调试器卡在 "Collecting Data"

c# - 从 C# 4.0 中的元组列表中查找和删除元组

python - 元组列表中的列表列表,重新排序

python - 将少量 python 嵌入到批处理脚本中

Python:在运行时创建生成器

c# - 有没有更快的方法来克隆项目列表?

python - 在二维数组中查找重复数组并将数字添加到元组中

python - 如何获取用户输入来引用 Python 中的变量?

python - 如何比较列表列表中的元素?