首页 > 解决方案 > "TypeError: 'type' object is not subscriptable" in a function signature

问题描述

Why am I receiving this error when I run this code?

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))

标签: pythonpython-3.xlisttypeerrortype-hinting

解决方案


该表达式list[int]试图下标 object 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):

推荐阅读