"TypeError:“类型"对象不可下标"在功能签名中 [英] "TypeError: 'type' object is not subscriptable" in a function signature

查看:41
本文介绍了"TypeError:“类型"对象不可下标"在功能签名中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

表达式 list [int] 试图对对象 type .由于 type 没有定义 __ getitem__ 方法,你不能做list[...].

The expression list[int] is attempting to subscript the object list, which is a class. Class objects are of the type of their metaclass, which is type in this case. Since type does not define a __getitem__ method, you can't do list[...].

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

To do this correctly, you need to import typing.List and use that instead of the built-in list in your type hints:

from typing import List

...


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

如果要避免多余的导入,可以简化类型提示以排除泛型:

If you want to avoid the extra import, you can simplify the type hints to exclude generics:

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

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

Alternatively, you can get rid of type hinting completely:

def twoSum(self, nums, target):

这篇关于"TypeError:“类型"对象不可下标"在功能签名中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆