Pythonでは、”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]
のような表記がサポートされていないためです。Python 3.9以降ではこの表記がサポートされています。
このエラーを解決するためには、以下のようにtyping.List
をインポートし、それを使用して型ヒントを指定します。
from typing import List
def twoSum(self, nums: List[int], target: int) -> List[int]:
# ...
また、型ヒントを省略することも可能です。
def twoSum(self, nums, target):
# ...
以上が、Pythonでの”TypeError: ‘type’ object is not subscriptable”エラーの解決方法についての説明です。この情報が役立つことを願っています。