为什么运行此代码时收到此错误?
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<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):
将@Nerxis的注释提升为答案。
对于Python 3.7和3.8,添加:
from __future__ import annotations
作为您第一次导入模块。
虽然使用List
而不是list
的公认答案是好的,但当您需要使用pd.Series[np.int64]
时,它对您没有帮助。请使用以上内容。
上面给出的答案是"疯狂的物理学家;有效,但3.9中关于新功能的这一页表明;list[int]";也应该起作用。
https://docs.python.org/3/whatsnew/3.9.html
但它对我不起作用。也许mypy还不支持3.9的这个功能。
摘要
代码中表示-> list[int]
的部分是函数返回类型的类型注释。这是一种特殊的表示法,第三方工具可以使用它来对代码进行一些基本的静态类型检查。就Python本身而言,它对代码的影响是向函数添加一些元数据:
>>> def example() -> list[int]:
... pass
...
>>> 'return' in example.__annotations__
True
Python本身不会执行任何类型检查。
类似地,: list[int]
部分是twoSum
的nums
参数的类型注释。
根据Python版本的不同,可能不接受此特定注释。
Python 3.9及以上版本
该错误无法重现。-> list[int]
声明函数旨在返回一个包含所有整数值的列表,: list[int]
声明应该为nums
传递另一个这样的列表。这些提示允许像MyPy这样的第三方工具在编译或运行代码之前查找问题。
Python 3.7或3.8
此注释未按原样接受。有两种解决方法:
- 使用
__future__
导入来访问";注释的延迟评估";PEP 563中描述的行为:
# At the top of the code, along with the other `import`s
from __future__ import annotations
- 使用标准库
typing
模块中定义的相应类:
# At the top of the code
from typing import List
# when annotating the function
def twoSum(self, nums: List[int], target: int) -> List[int]:
注意List
中的大写字母L。
Python 3.5和3.6
不支持__future__
注释。使用typing
模块。
Python 3.4及以下版本
根本不支持类型批注。只需移除它们:
def twoSum(self, nums, target):
再次记住,Python本身对注释没有做任何有意义的事情。它们不会导致代码为无效参数引发异常,也不会将它们转换为正确的类型,或者其他类似的事情。它们仅用于第三方工具,完全可选,除非其他第三方刀具强制使用它们。