Lyn*_*nnH 528 python tuples python-2.7
我正在尝试将列表转换为元组.
当我谷歌它,我发现很多答案类似于:
l = [4,5,6]
tuple(l)
Run Code Online (Sandbox Code Playgroud)
但如果我这样做,我收到此错误消息:
TypeError:'tuple'对象不可调用
我该如何解决这个问题?
roo*_*oot 787
它应该工作正常.不要使用tuple,list或其他特殊的名字作为变量名.这可能是导致你的问题的原因.
>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)
Run Code Online (Sandbox Code Playgroud)
unu*_*tbu 107
扩展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)
Run Code Online (Sandbox Code Playgroud)
但是,如果您重新定义tuple为元组而不是type tuple:
In [4]: tuple = tuple(l)
In [5]: tuple
Out[5]: (4, 5, 6)
Run Code Online (Sandbox Code Playgroud)
然后你得到一个TypeError,因为元组本身不可调用:
In [6]: tuple(l)
TypeError: 'tuple' object is not callable
Run Code Online (Sandbox Code Playgroud)
您可以tuple通过退出并重新启动解释器来恢复原始定义,或者(感谢@glglgl):
In [6]: del tuple
In [7]: tuple
Out[7]: <type 'tuple'>
Run Code Online (Sandbox Code Playgroud)
Roh*_*ain 28
你可能做过这样的事情:
>>> 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)
Run Code Online (Sandbox Code Playgroud)
这是问题...因为你已经使用了一个tuple变量来保存tuple (45, 34)更早...所以,现在tuple是一个object类型tuple...
它不再是一个type,因此,它不再是Callable.
Never使用任何内置类型作为变量名称...您还可以使用任何其他名称.使用任意名称代替变量......
Jim*_*ard 22
要添加另一个替代方法tuple(l),从Python> =开始,3.5您可以执行以下操作:
t = *l, # or t = (*l,)
Run Code Online (Sandbox Code Playgroud)
总之,有点快,但可能是从可读性受到影响.
这基本上解压缩了l由于存在单个逗号而创建的元组文字中的列表,.
Ps:您收到的错误是由于屏蔽了名称,tuple即您在某个地方分配了名称元组,例如tuple = (1, 2, 3).
使用del tuple你应该很高兴.
我找到了许多最新的答案,并且得到了正确答案,但会为答案添加一些新内容。
在蟒蛇有无限的方法可以做到这一点,这里有一些情况下,
正常的方式
>>> l= [1,2,"stackoverflow","python"]
>>> l
[1, 2, 'stackoverflow', 'python']
>>> tup = tuple(l)
>>> type(tup)
<type 'tuple'>
>>> tup
(1, 2, 'stackoverflow', 'python')
Run Code Online (Sandbox Code Playgroud)
聪明的方法
>>>tuple(item for item in l)
(1, 2, 'stackoverflow', 'python')
Run Code Online (Sandbox Code Playgroud)
请记住,元组是不变的,用于存储有价值的东西。例如,密码,密钥或哈希存储在元组或字典中。如果需要刀,为什么要用剑切苹果。明智地使用它,还可以使您的程序高效。
| 归档时间: |
|
| 查看次数: |
698180 次 |
| 最近记录: |