我正在尝试创建一个新字典,其中将列出树的物种以及该物种的 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 (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'