在Python中将列表转换为元组

问题描述 投票:488回答:5

我正在尝试将列表转换为元组。

当我谷歌它,我发现很多答案类似于:

l = [4,5,6]
tuple(l)

但如果我这样做,我收到此错误消息:

TypeError:'tuple'对象不可调用

我该如何解决这个问题?

python python-2.7 tuples
5个回答
756
投票

它应该工作正常。不要使用tuplelist或其他特殊名称作为变量名称。这可能是导致你的问题的原因。

>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)

106
投票

扩展eumiro的评论,通常tuple(l)将列表l转换为元组:

In [1]: l = [4,5,6]

In [2]: tuple
Out[2]: <type 'tuple'>

In [3]: tuple(l)
Out[3]: (4, 5, 6)

但是,如果你重新定义tuple是一个元组而不是type tuple

In [4]: tuple = tuple(l)

In [5]: tuple
Out[5]: (4, 5, 6)

然后你得到一个TypeError,因为元组本身不可调用:

In [6]: tuple(l)
TypeError: 'tuple' object is not callable

您可以通过退出并重新启动解释器来恢复tuple的原始定义,或者(感谢@glglgl):

In [6]: del tuple

In [7]: tuple
Out[7]: <type 'tuple'>

27
投票

你可能做过这样的事情:

>>> tuple = 45, 34  # You used `tuple` as a variable here
>>> tuple
(45, 34)
>>> l = [4, 5, 6]
>>> tuple(l)   # Will try to invoke the variable `tuple` rather than tuple type.

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    tuple(l)
TypeError: 'tuple' object is not callable
>>>
>>> del tuple  # You can delete the object tuple created earlier to make it work
>>> tuple(l)
(4, 5, 6)

这是问题...因为你使用了tuple变量来更早地持有tuple (45, 34) ...所以,现在tuple现在是object类型的tuple ...

它不再是type因此,它不再是Callable

Never使用任何内置类型作为您的变量名称...您还可以使用任何其他名称。使用任意名称代替变量......


19
投票

要添加tuple(l)的另一种替代方法,从Python> = 3.5开始,您可以:

t = *l,  # or t = (*l,) 

简而言之,快一点但可能会有可读性。

这基本上解压缩了由于存在单个逗号l而创建的元组文字中的列表,


P.s:您收到的错误是由于掩盖了名称tuple,即您分配给某个地方的名字元组,例如tuple = (1, 2, 3)

使用del tuple你应该很高兴。


5
投票

我发现许多答案是最新的并且得到了适当的回答,但会在答案堆栈中添加新内容。

在python中有无限的方法可以做到这一点,这里有一些实例 正常的方式

>>> l= [1,2,"stackoverflow","python"]
>>> l
[1, 2, 'stackoverflow', 'python']
>>> tup = tuple(l)
>>> type(tup)
<type 'tuple'>
>>> tup
(1, 2, 'stackoverflow', 'python')

聪明的方式

>>>tuple(item for item in l)
(1, 2, 'stackoverflow', 'python')

记住元组是不可变的,用于存储有价值的东西。例如,密码,密钥或散列存储在元组或字典中。如果需要刀,为什么要用剑切苹果。明智地使用它,它也将使您的程序高效。

© www.soinside.com 2019 - 2024. All rights reserved.