我正在嘗試創建一個新的字典,它將列出一棵樹的物種以及該物種的DBH。每個物種都會有多個DBH。它從文本文件中提取這些信息。AttributeError:'float'對象沒有屬性'append' - Python字典
創建第一個字典的部分正在工作(列出了每個字典的種類和數量),但我無法得到它爲每個物種附加DBH。我繼續得到錯誤AttributeError:'float'對象沒有屬性'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'
請包括回溯。這將顯示引發異常的確切路線。它顯然是包含'.append()'的行之一。正如msg所說的錯誤,你會發現你試圖追加到一個浮點數。 –
Traceback(最近呼叫的最後一個): RunScript中的第326行文件「C:\ Python27 \ ArcGIS10.1 \ Lib \ site-packages \ pythonwin \ pywin \ framework \ scriptutils.py」執行代碼對象在__main __.__ dict__ mydict2 [species] .append(DBH) AttributeError:'float'object has no attribute'append' – user2923636
因此,'mydict2 [species],第40行,在 '是一個浮動。你期望它是一個浮動嗎?你不能追加到浮動。 –