首页 文章

在Python中将列表转换为元组

提问于
浏览
434

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

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

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

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

TypeError:'tuple'对象不可调用

我该如何解决这个问题?

5 回答

  • 97

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

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

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

    smart way

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

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

  • 16

    它应该工作正常 . 请勿使用 tuplelist 或其他特殊名称作为变量名称 . 它's probably what'导致你的问题 .

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

    要添加 tuple(l) 的另一个替代方法,从Python> = 3.5 开始,您可以执行以下操作:

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

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

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


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

    使用 del tuple 你应该很高兴 .

  • 24

    扩展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'>
    
  • 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)
    

    这是问题...因为你已经使用 tuple 变量来保持 tuple (45, 34) 更早......所以,现在 tupleobject 类型 tuple 现在......

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

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

相关问题