【问题标题】:"TypeError: 'type' object is not subscriptable" in a function signature函数签名中的“TypeError:‘type’对象不可下标”
【发布时间】:2020-12-07 03:17:30
【问题描述】:

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

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

【问题讨论】:

  • 不熟悉你使用的语法。你不是说def twoSum(nums, target):吗?
  • @ewong。它是类型提示,现在风靡一时
  • 此语法仅从 Python 3.9 开始支持
  • 正如其他提到的,这将在 Python 3.9 中得到支持,但如果你想更早使用这个解决方案(如 list[int]),你可以通过将 from __future__ import annotations 作为第一个导入来实现模块(由于PEP 563,可从 Python 3.7+ 获得)。

标签: python python-3.x list typeerror type-hinting


【解决方案1】:

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

【讨论】:

  • Typing 没有使用元类,因为像 3.7 一样,因为键入使用不同元类的代码是不可能的。 __class_getitem__ 已添加,用于下标类型。此外,您的答案在 Python 3.9+ 中是完全错误的。
  • 这刚刚解决了我的问题。很多!
  • @masher。当事情成功时,总是很高兴听到。祝你好运!
【解决方案2】:

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

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

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

【讨论】:

  • 我的代码在 3.9 中使用 list[int] 运行良好(没有运行时错误),但仍然无法使用 mypy 正确检查类型。
  • 这里一样,list[int] 在 3.9 中工作正常,但在 Python3.8(特别是 AWS Lambda Python3.8 运行时)下会引发 OP 错误。
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
相关资源
最近更新 更多