函数签名中的“TypeError:‘type’对象不可订阅”

新手上路,请多包涵

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

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

原文由 yuenster 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 845
2 个回答

以下答案仅适用于 Python < 3.9

表达式 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):

原文由 Mad Physicist 发布,翻译遵循 CC BY-SA 4.0 许可协议

“Mad Physicist”上面给出的答案是有效的,但是这个关于 3.9 新特性的页面建议“list[int]”也应该有效。

https://docs.python.org/3/whatsnew/3.9.html

但这对我不起作用。可能mypy还不支持3.9的这个特性。

原文由 Mark Volkmann 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题