gpt4 book ai didi

python - "TypeError: ' 在函数签名中输入 ' object is not subscriptable"

转载 作者:行者123 更新时间:2023-12-04 11:20:41 25 4
gpt4 key购买 nike

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

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]正在尝试为对象添加下标 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 - "TypeError: ' 在函数签名中输入 ' object is not subscriptable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63460126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com