Python 迭代 list["a","b","c"] 时出现错误“'type' 对象没有属性 '__getitem__'”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29584749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error "'type' object has no attribute '__getitem__'" when iterating over list["a","b","c"]
提问by April
I'm new to Python and I keep getting this error:
我是 Python 新手,我不断收到此错误:
TypeError: 'type' object has no attribute '__getitem__'
when I try to run this code:
当我尝试运行此代码时:
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")
What am I doing wrong?
我究竟做错了什么?
采纳答案by Blacklight Shining
This line is your problem:
这一行是你的问题:
lst=list["ram","bak","cat","fas","far","fmk","sup","gro","ebt"]
Python interprets what's in those square brackets as a key to get an item from what's just before them—in this case, getting the item with key "ram", "bak", ...
from list
. And, of course, the list
class isn't a container and doesn't have any items!
Python 将这些方括号中的内容解释为一个键,以便从它们之前的内容中获取一个项目——在这种情况下,"ram", "bak", ...
从list
. 而且,当然,list
该类不是容器,也没有任何物品!
Remove the leading list
, and you get a list literal, which is probably what you want.
删除前导list
,你会得到一个列表文字,这可能是你想要的。
list_ = ["ram", "bak", "cat", "fas", "far", "fmk", "sup", "gro", "ebt"]
See the documentation on list
sfor more information on how to create them.
有关如何创建它们的更多信息,请参阅有关list
s的文档。
See also the official Python style guide, which states
另请参阅官方 Python 样式指南,其中指出
names that would otherwise collide with keywords or builtins (like
list
) should have single underscores appended rather than being mangled (list_
instead oflst
orlizt
), except in the case ofcls
container literals and function calls should have spaces after the commas (
"ram", "bak"
instead of"ram","bak"
)
否则会与关键字或内置函数(如
list
)发生冲突的名称应附加单个下划线而不是被破坏(list_
而不是lst
或lizt
),除非是cls
容器文字和函数调用应该在逗号后有空格(
"ram", "bak"
而不是"ram","bak"
)
回答by Julien Spronck
To define a list,
要定义一个列表,
lst=["ram","bak","cat","fas","far","fmk","sup","gro","ebt"]
or
或者
lst=list(...)
but list
is a type, which you can call with parenthesis but you can't get an item from list
using the square brackets.
butlist
是一种类型,您可以使用括号调用它,但不能list
使用方括号获取项目。