在Python中将列表转换为元组
我试图将列表转换为元组。
当我谷歌,我发现了很多类似的答案:
l = [4,5,6]
tuple(l)
但如果我这样做,我会得到这个错误信息:
TypeError:'tuple'对象不可调用
我该如何解决这个问题?
它应该工作正常。 不要使用tuple , list或其他特殊名称作为变量名称。 这可能是什么导致你的问题。
>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)
扩展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重新定义为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'>
你可能做了这样的事情:
>>> 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是一个类型为tuple的object ,现在...
它不再是一种type ,因此它不再是Callable 。
Never使用任何内置类型作为变量名称...您有任何其他名称可供使用。 改用任何任意名称代替...
