我对Python非常陌生,在从类的属性中删除重复值时遇到了一些麻烦(我认为这是正确的术语)。从类变量的属性中删除重复对象
具体而言,我想删除同一年的每个值。我应该注意到,我只打印前四个值并搜索前四个值。属性中的数据实际上是以Yearmonthday格式(例如:19070101是1907年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]
我得到这个错误:
回溯(最后最近一次调用): 文件 “project.py” 61行,在 如果len(date [studyPRP.DATE] [0:4]): KeyError:'19770509'
可以修复一个关键错误(这意味着一个值不在列表中,但它是用于我的数据)通过使用设置功能(或者我读过),但我有30,000件我正在处理的信息,似乎你必须手动输入信息,所以这不适合我。
任何帮助都将不胜感激
很抱歉,如果这是令人困惑的或无意义的,因为我感到非常新的Python。
那么什么是数据类型? 'filedat'中有什么?请给[mcve],否则没人能帮忙。 – jonrsharpe
我编辑了包含该信息的代码。感谢您的回应。 – Preston
注*最小*,并给予完整的追溯。 – jonrsharpe