In [1]: l = [4,5,6]
In [2]: tuple
Out[2]: <type 'tuple'>
In [3]: tuple(l)
Out[3]: (4, 5, 6)
但是,如果您已将 tuple 重新定义为元组而不是 typetuple :
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'>
4
你可能做过这样的事情:
>>> 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)
5 回答
我发现许多答案是最新的并且得到了适当的回答,但会为答案堆栈添加新内容 .
在python中有无限的方法可以做到这一点,这里有一些实例
正常的方式
smart way
记住元组是不可变的,用于存储有 Value 的东西 . 例如,密码,密钥或散列存储在元组或字典中 . 如果需要刀,为什么要用剑切苹果 . 明智地使用它,也会使您的程序高效 .
它应该工作正常 . 请勿使用
tuple
,list
或其他特殊名称作为变量名称 . 它's probably what'导致你的问题 .要添加
tuple(l)
的另一个替代方法,从Python> =3.5
开始,您可以执行以下操作:简而言之,有点快,但可能会有可读性 .
这基本上解压缩了由于存在单个逗号
,
而创建的元组文字中的列表l
.P.s:您收到的错误是由于屏蔽了名称
tuple
,即您分配给某个地方的名称元组,例如tuple = (1, 2, 3)
.使用
del tuple
你应该很高兴 .扩展eumiro的评论,通常
tuple(l)
会将列表l
转换为元组:但是,如果您已将
tuple
重新定义为元组而不是type
tuple
:然后你得到一个TypeError,因为元组本身不可调用:
您可以通过退出并重新启动解释器来恢复
tuple
的原始定义,或者(感谢@glglgl):你可能做过这样的事情:
这是问题...因为你已经使用
tuple
变量来保持tuple (45, 34)
更早......所以,现在tuple
是object
类型tuple
现在......它不再是
type
因此,它不再是Callable
.Never
使用任何内置类型作为变量名称...您还可以使用任何其他名称 . 使用任意名称代替变量......