python - "TypeError: 'type' object is not subscriptable" in a function signature
问题描述
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]
试图下标 object 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):
推荐阅读
- python - 使用循环根据特定列值识别数据框中的所有实例
- unique-ptr - 为什么我收到一个错误,即“virtual Derived::~Derived()”在此上下文中受到保护?
- react-native - 在 React Native 中从精灵表渲染像素化精灵
- bash - 每次我推入远程存储库时,创建一个 Git Hook 以在另一个文件夹中提取数据
- android - 评估根项目“android”时出现问题。飞镖
- java - How to activate a HttpServlet class?
- java - JavaFX 使用 PDFBox 将 PDF 文件转换为 PNG 文件
- c++ - 在 Windows 上使用 gcc 为 Node.js 编译 C++ 附加组件
- azure - Get-AzureADServiceAppRoleAssignment 不返回代表其他租户中 AAD 应用程序的 SP 的角色分配
- java - 如何在我的 AWS AMI Ec2 实例上安装 JDK 17?