在Python中将列表转换为元组

rim*_*ire 1 python tuples list python-3.x

>>> list=['a','b']
>>> tuple=tuple(list)
>>> list.append('a')
>>> print(tuple)
('a', 'b')
>>> another_tuple=tuple(list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
Run Code Online (Sandbox Code Playgroud)

为什么我不能将列表'list'转换为元组?

jpp*_*jpp 6

难道不是名称类别后的变量.在您的示例中,您使用list和执行此操作tuple.

您可以重写如下:

lst = ['a', 'b']
tup = tuple(lst)
lst.append('a')
another_tuple = tuple(lst)
Run Code Online (Sandbox Code Playgroud)

按行说明

  1. 创建一个包含2个项目的可变对象列表.
  2. 将列表转换为元组,它是一个不可变对象,并分配给一个新变量.
  3. 取原始列表并附加一个项目,因此原始列表现在有3个项目.
  4. 从新列表中创建一个元组,返回3个元组的元组.

您发布的代码无法按预期工作,因为:

  • 当您调用时another_tuple=tuple(list),Python会尝试将您tuple在第二行中创建的内容视为函数.
  • tuple 变量不是调用.
  • 因此,Python退出TypeError: 'tuple' object is not callable.