AttributeError:'float'对象没有属性'append' - Python Dictionary

时间:2013-10-26 18:52:39

标签: python dictionary append

我正在尝试创建一个新的字典,它将列出树的种类以及该种的DBH。每个物种将有多个DBH。它从文本文件中提取此信息。

创建第一个字典的部分正在工作(列出每个字典的种类和数量),但我不能让它为每个物种附加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

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'

1 个答案:

答案 0 :(得分:4)

对我来说很简单。

mydict2[species].append(DBH)

在此处初始化:

mydict2[species]=DBH

来自这里:

DBH = row[3]

来自这里:

data.append([float(myline[0]),float(myline[1]),myline[2].rstrip(),float(myline[3].rstrip())]) 

所以这是一个浮动。并且你不能追加浮点数,所以你得到了那个错误。

我想你可能想要列出这些DBH:

mydict2[species] = [DBH]

或者,您可以查看defaultdict

from collections import defaultdict
mydict2 = defaultdict(list)
mydict2[species].append(DBH)

你可以删除if-stmt - 代码会在没有列表的情况下列出并始终追加。

我还会考虑使用csv库来处理制表符分隔文件。


以下是我想象您将代码更改为:

import csv
from collections import defaultdict

def read_my_data(filepath="C:\\temp\\rdu_forest1.txt"):
    with open(filepath, 'r') as myfile:
        reader = csv.reader(myfile, delimiter='\t')
        return [
            [float(myline[0]),float(myline[1]),myline[2].rstrip(),float(myline[3].rstrip())]
            for row in reader
        ]

mydict2 = defaultdict(list)

for _, _, species, DBH  in read_my_data():
    mydict2[species].append(DBH)

mydict = {
    k: len(v)
    for k, v in mydict2.iteritems()
}

print mydict

并非我实际上已经运行过这个或任何东西。如果您仍然遇到defaultdict的问题,请与我们联系。