【问题标题】:The argument for my for loops is being called a tuple by my computer, but not by other compilers我的 for 循环的参数被我的计算机称为元组,但不被其他编译器
【发布时间】:2020-09-09 19:45:57
【问题描述】:

所以我正在尝试制作高度图生成器,我拥有的一个功能是初始化一个值矩阵。

def initializeHeightMatrix(image_size):
    height_matrix = []
    for i in range(0,image_size):
        row = []
        for j in range(0, image_size):
            row.append(0)
        height_matrix.append(row)
    return height_matrix

matrix = initializeHeightMatrix(4)
print(matrix)

这在以前肯定是有效的,我尝试在基于浏览器的编译器上运行它。它在那里工作得非常好,但是每当我尝试在我的计算机上运行它时,我都会收到错误:

File "heightmapgenerator.py", line 31, in generateHeightMatrix
    for i in range(0,image_size):
TypeError: 'tuple' object is not callable

所以我的范围现在是元组?

【问题讨论】:

  • image_size 是一个元组。这就是它可能的意思。尽管您使用 (4) 调用它。可以调试到第 31 行并检查 image_size 的类型吗?
  • 正如@Sheradil 提到的,您的image_size 变量分配看起来如何?
  • 你可能已经重新定义了内置函数rangetype(range) 报告什么?重新启动控制台/解释器很可能会解决问题。
  • @DYZ 绝对是这样。

标签: python for-loop matrix tuples typeerror


【解决方案1】:

Python 有内置函数和关键字。在我的 IDE 或最常用的文本编辑器中,关键字的颜色与内置的颜色不同,内置的颜色与程序定义的变量名称不同。 range 这个词是内置的,因为它与 builtin range class 相关联。虽然 python 会让你重新分配内置函数,但除非你想显式地修改它们的功能,否则这样做通常是不明智的。要查看所有内置函数,只需尝试:

import builtins

print(dir(builtins))

同样,您可以通过执行以下操作查看所有关键字(如果您尝试修改其中之一,您的编译器应该会引发语法错误):

import keyword

print(keyword.kwlist)

在你的代码中的某个地方(可能是在不知不觉中),你可能做了类似的事情:

range = ('my', 'tuple')

为了说明问题,试试这个:

print(type(range)) # prints the builtin <class 'range'>

# then reassign range
range = ('my', 'tuple')

print(type(range)) # now prints <class 'tuple'>

# what is interesting is that tuples are iterable
# and you can use them in a for loop
for item in range:
    print(item)

# however, if you try and use your new tuple definition of range
# as you would use the builtin range class, you will get an error
try:
    for item in range(0, 100):
         print(item)
except TypeError:
    print("This doesn't work")

# this is analogous to writing something like
try:
    (1, 2, 3, 4, 5, 6)(0, 100)
except TypeError:
    print("Bad programming alert!") 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多