【发布时间】:2013-11-05 19:07:58
【问题描述】:
我正在尝试创建一个新字典,其中将列出一棵树的物种以及该物种的 DBH。每个物种将有多个 DBH。它从文本文件中提取此信息。
创建第一个字典的部分正在工作(列出物种和每个物种的数量),但我无法让它为每个物种附加 DBH。我继续收到错误 AttributeError: 'float' object has no attribute 'append'。我已经搜索和搜索并尝试了多种方法,但无法使其正常工作。
import string, os.path, os, sys
filepath = "C:\\temp\\rdu_forest1.txt"
data=[]
#Open the text file
myfile=open(filepath,'r')
#Read the text file
myfile.readline() #read the field name line
row = myfile.readline()
count = 0
while row:
myline = row.split('\t') #Creat a list of the values in this row. Columns are tab separated.
#Reads a file with columns: Block Plot Species DBH MerchHeight
data.append([float(myline[0]),float(myline[1]),myline[2].rstrip(),float(myline[3].rstrip())])
#rstrip removes white space from the right side
count = count + 1
row = myfile.readline()
myfile.close()
mydict={}
mydict2={} #Create an emyty mydict2 here *********
for row in data: # for each row
# create or update a dictionary entry with the current count for that species
species = row[2]#Species is the third entry in the file
DBH = row[3] #DBH is the fourth entry in the file
if mydict.has_key(species): #if a dictionary entry already exists for this species
#Update dict for this species
cur_entry = mydict[species]
cur_entry = int(cur_entry)+1
mydict[species] = cur_entry
#update mydict2 here *********
mydict2[species].append(DBH)
else:#This is the first dictionary entry for this species
#Create new dict entry with sums and count for this species
mydict[species]=1
mydict2[species]=DBH #Add a new entry to mydict2 here *********
print mydict
这里是 TraceBack
Traceback (most recent call last):
File "C:\Python27\ArcGIS10.1\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
exec codeObject in __main__.__dict__
File "E:\Python\16\dictionary.py", line 40, in <module>
mydict2[species].append(DBH)
AttributeError: 'float' object has no attribute 'append'
【问题讨论】:
-
请包括回溯。这将显示引发异常的确切行。它显然是包含
.append()的行之一。正如错误消息所说,您会发现您正在尝试附加到浮点数。 -
Traceback(最近一次调用最后):文件“C:\Python27\ArcGIS10.1\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py”,第 326 行,在 RunScript exec main.__dict__ 中的 codeObject 文件“E:\Python\16\dictionary.py”,第 40 行,在
mydict2[species].append(DBH) AttributeError: 'float' object has no属性“追加” -
所以
mydict2[species]是一个浮点数。你希望它是一个浮点数吗?您不能附加到浮点数。 -
这很奇怪吗?我完全没有错误。
-
这是 mydict 的值:{'LOB': 95, 'BE': 1, 'WD': 10, 'WO': 95, 'HK': 19, 'YP': 33,“POP”:12,“RB”:3,“RM”:71,“ASH”:2,“LP”:696,“SLP”:1,“VP”:1,“SRW”:2, 'SHL':17,'CV':1,'RO':82,'MPL':13,'SP':1,'SW':11,'MW':1,'SL':21,'SG ': 82} 我希望 mydict2 是:{'LOB': [102, 14, 203], 'BE': [212, 232]...} 第一个显示物种和该物种的树木数量.第二个显示该物种的物种和每棵树的直径。也许有更好的方法来获取这些值。我对这个概念完全陌生。
标签: python dictionary append