【问题标题】:AttributeError: 'float' object has no attribute 'append' - Python DictionaryAttributeError:'float'对象没有属性'append' - Python Dictionary
【发布时间】: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


【解决方案1】:

对我来说看起来很简单。

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 时仍有问题,请告诉我。

【讨论】:

  • 这是我在使用 defaultdict 时得到的: defaultdict(, {'LP': [11.0]}) 它应该列出更多的物种和直径。我确定我用错了。
  • 如果我使用 mydict2[species] = [DBH],它只会保存一个直径值,而不是列出该物种的所有值。
猜你喜欢
  • 2018-06-22
  • 2015-08-16
  • 2017-08-14
  • 2015-03-08
  • 2019-12-31
  • 2021-03-11
  • 2015-03-28
  • 2018-10-02
  • 2019-03-31
相关资源
最近更新 更多