【发布时间】: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