【问题标题】:Converting list to tuple in Python [duplicate]在Python中将列表转换为元组[重复]
【发布时间】:2018-10-14 16:56:57
【问题描述】:
>>> 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

为什么我不能将列表“列表”转换为元组?

【问题讨论】:

  • 因为你已经将tuple 重载到你的元组变量,当它是一个__builtin__ 函数时。

标签: python python-3.x list tuples typeerror


【解决方案1】:

不要在类之后命名变量。在您的示例中,您可以同时使用 listtuple

你可以改写如下:

lst = ['a', 'b']
tup = tuple(lst)
lst.append('a')
another_tuple = tuple(lst)

逐行解释

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

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

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

【讨论】:

  • 很好的解释!
猜你喜欢
  • 2017-09-10
  • 2017-03-24
  • 2017-07-30
  • 2016-01-29
  • 1970-01-01
  • 2010-12-25
  • 2014-07-14
  • 2012-10-01
  • 2019-05-02
相关资源
最近更新 更多