【问题标题】:To make tuple but it's hard制作元组但很难
【发布时间】:2017-11-17 09:56:35
【问题描述】:

我只想制作元组来使用列表 所以,

list1 = [1,2]
a = tuple(list1)

我使用了这段代码,但它是错误的..

TypeError: 'tuple' 对象不可调用

为什么不做元组呢?

【问题讨论】:

  • 为我工作。修改后重试。
  • 在代码中的某处,您定义了一个 type tuple named tuple 的变量。当您再次尝试使用该名称时,该名称会遮盖内置的 tuple不要隐藏内置函数名称

标签: python-2.7 list python-3.x types tuples


【解决方案1】:

正如你在这个问题中看到的Convert list to tuple in Python

您肯定调用了像listtuple 这样的变量,这些词是内置类型并且可以重新定义,这是一个很大的错误来源

举例:

list = [1,3]
tuple = (2,3)

只有这种代码和平,工作正常,但如果你尝试这样做

list = [1,3]
tuple = (2,3)
a = tuple(list)

你会得到错误

TypeError: 'tuple' 对象不可调用

其他可能的情况:

list = [1,2,3,4]
print(list)

$[1,2,3,4]

但是:

list = [1,2,3,4]
print(list)
other_list = list((1,2,3,4))
print(other_list)

TypeError: 'list' 对象不可调用

因为你重新定义了list,现在是一个对象,对象[1,2,3,4]

解决方法很简单,重命名你的变量,例如:

lst = [1,3]
tpl = (4,5)
a = tuple(lst)
print(a)

$(1,3)

【讨论】:

  • @wooojuns 如果可以,请添加问题中缺少的代码部分,即中断的部分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-26
  • 2011-03-10
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2011-07-28
相关资源
最近更新 更多