【发布时间】:2016-04-27 16:58:44
【问题描述】:
我对 python 非常陌生,并且在从类的属性中删除重复值时遇到了一些麻烦(我认为这是正确的术语)。
具体来说,我想删除同一年份的每个值。我应该注意,我只打印前四个值并搜索前四个值。属性中的数据实际上是 Yearmonthday 格式(例如:19070101 是 1907 年 1 月 1 日)。
无论如何,这是我的代码:
import csv
import os
class Datatype:
'Data from the weather station'
def __init__ (self, inputline):
[ self.DATE,
self.PRCP] = inputline.split(',')
filename ='LAWe.txt'
LAWd = open(filename, 'r')
LAWefile = LAWd.read()
LAWd.close()
'Recognize the line endings for MS-DOS, UNIX, and Mac and apply the .split() method to the string wholeFile'
if '\r\n' in LAWefile:
filedat = LAWefile.split('\r\n') # the split method, applied to a string, produces a list
elif '\r' in LAWefile:
filedat = LAWefile.split('\r')
else:
filedat = LAWefile.split('\n')
collection = dict()
date= dict()
for thisline in filedat:
thispcp = Datatype(thisline) # here is where the Datatype object is created (running the __init__ function)
collection[thispcp.DATE] = thispcp # the dictionary will be keyed by the ID attribute
for thisID in collection.keys():
studyPRP = collection[thisID]
if studyPRP.DATE.isdigit():
list(studyPRP.DATE)
if len(date[studyPRP.DATE][0:4]):
pass #if year is seen once, then skip and go to next value in attribute
else:
print studyPRP.DATE[0:4] #print value in this case the year)
date[studyPRP.DATE]=studyPRP.DATE[0:4]
我收到此错误:
Traceback(最近一次调用最后一次): 文件“project.py”,第 61 行,在 如果 len(日期[studyPRP.DATE][0:4]): 键错误:'19770509'
一个关键错误(这意味着一个值不在列表中?但它是针对我的数据的)可以通过使用 set 函数来修复(或者我已经阅读过),但我有 30,000 条信息我正在处理,看来您必须手动输入该信息,所以这不是我的选择。
任何帮助都将不胜感激
对不起,如果这令人困惑或荒谬,因为我对 python 非常陌生。
【问题讨论】:
-
那么
Datatype是什么?filedat中有什么内容?请给minimal reproducible example,否则没人能帮忙。 -
我编辑了代码以包含该信息。感谢您的回复。
-
注意minimal,并给出完整的回溯。
标签: python class dictionary attributes key