遍历列表 ["a"、"b"、"c"] 时出现错误“'type' 对象没有属性 '__getitem__'”

Error "'type' object has no attribute '__getitem__'" when iterating over list["a","b","c"]

我是 Python 的新手,我一直收到此错误:

TypeError: 'type' object has no attribute '__getitem__'

当我尝试 运行 此代码时:

import arcpy,os
from arcpy import env
from arcpy.sa import*
env.workspace="F:\U of M\good good study\python\fl\fl"
inFeatures="foodpts.shp"
lst=list["ram","bak","cat","fas","far","fmk","sup","gro","ebt"]
for item in lst:
    populationField=item
    cellsize=100
    searchRadius=805
    arcpy.CheckOutExtension("Spatial")    
    outKernelDensity=KernelDensity(inFeatures,populationField,cellsize,searchRadius,  "SQUARE_KILOMETERS")
    outKernelDensity.save("F:\U of M\good good study\python\fl\fl\kernal")

我做错了什么?

这一行是你的问题:

lst=list["ram","bak","cat","fas","far","fmk","sup","gro","ebt"]

Python 将这些方括号中的内容解释为从它们之前的内容中获取项目的键——在本例中,从 list 中获取具有键 "ram", "bak", ... 的项目。当然,list class 不是容器,也没有任何物品!

删除前导 list,您将得到一个列表文字,这可能就是您想要的。

list_ = ["ram", "bak", "cat", "fas", "far", "fmk", "sup", "gro", "ebt"]

有关如何创建它们的详细信息,请参阅 the documentation on lists

另见 the official Python style guide,其中指出

  • 否则会与关键字或内置函数(如 list)冲突的名称应该附加单个下划线而不是被破坏(list_ 而不是 lstlizt), 除了 cls

  • 容器文字和函数调用应该在逗号后有空格("ram", "bak" 而不是 "ram","bak"

要定义一个列表,

lst=["ram","bak","cat","fas","far","fmk","sup","gro","ebt"]

lst=list(...)

list 是一种类型,您可以使用括号调用它,但您无法使用方括号从 list 中获取项目。