函数签名中的“TypeError:'type'对象不可下标”

2023-11-20

为什么我在运行此代码时收到此错误?

Traceback (most recent call last):                                                                                                                                                  
  File "main.py", line 13, in <module>                                                                                                                                              
    def twoSum(self, nums: list[int], target: int) -> list[int]:                                                                                                                    
TypeError: 'type' object is not subscriptable
nums = [4,5,6,7,8,9]
target = 13

def twoSum(self, nums: list[int], target: int) -> list[int]:
        dictionary = {}
        answer = []
 
        for i in range(len(nums)):
            secondNumber = target-nums[i]
            if(secondNumber in dictionary.keys()):
                secondIndex = nums.index(secondNumber)
                if(i != secondIndex):
                    return sorted([i, secondIndex])
                
            dictionary.update({nums[i]: i})

print(twoSum(nums, target))

以下答案仅适用于 Python

表达方式list[int]正在尝试为对象添加下标list,这是一个类。类对象具有其元类的类型,即type在这种情况下。自从type没有定义一个__getitem__方法,你不能这样做list[...].

要正确执行此操作,您需要导入typing.List并使用它来代替内置的list在你的类型提示中:

from typing import List

...


def twoSum(self, nums: List[int], target: int) -> List[int]:

如果您想避免额外的导入,可以简化类型提示以排除泛型:

def twoSum(self, nums: list, target: int) -> list:

或者,您可以完全摆脱类型提示:

def twoSum(self, nums, target):
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

函数签名中的“TypeError:'type'对象不可下标” 的相关文章

随机推荐