【发布时间】:2020-12-17 04:09:31
【问题描述】:
我想编写一个 Python 程序来读取 csv 文件并存储在具有字符串键和浮点值的字典中。使用字典中的数据存储,我想计算平均幅度和深度。
aver_quake[k] = sum(v) / float(len(v))
以下是错误:
TypeError: +: 'int' 和 'str' 的操作数类型不受支持
地震.csv 文件示例
当地时间、幅度、深度 2020/03/18 08:57:41 MDT,3.6,8.3 2020/03/18 07:36:38 MDT,3.5,9.6 2020/03/21 10:59:31 MDT,3.4,10.3 2020/03/18 13:07:30 MDT,3.4,9
class Quake_Reader:
def __init__(self, mag, dep, __location = 'city'):
self.depth = dep
self.magnitude = mag
self.location = __location
def __get_location(self):
return self.location
def get_magnitude(self, __magnitude):
return __magnitude
def get_depth(self, __depth):
return __depth
""" Total Quake method calculate the total size in the data """
def total_quake(self):
return len(quake_list) - 1
# print("There are {} shakes in the data".format(len(quake_list) - 1))
# print("---" * 15)
""" String method call the total quake method print out the size of data"""
def __str__(self):
print("Total quakes in the data is: ", self.total_quake())
print("---" * 12)
""" Top ten magnitude"""
def top_ten(self):
k = Counter(quake_list)
high = k.most_common(10)
print("Top 10 largest quakes in the data are: ")
print("-"*38)
[print(key, value) for key, value in high]
""" Average magnitude method"""
def avg_magn(self):
aver_quake = {}
for k, v in quake_list.items():
aver_quake[k] = sum(v) / float(len(v))
""" Main function """
if __name__ == '__main__':
# instantiate quake reader class
qr = Quake_Reader(0,0,"city")
try:
# create an empty dictionary
quake_list = dict()
# open the source data
with open('earthquakes.csv', 'r') as csv_file:
# loop through the file and store the data in an empty quake
# dictionary
for key, value in enumerate(csv_file):
line, *lines = value.split(",")
if line in quake_list:
quake_list[key] = lines
else:
quake_list[line] = lines
# closed the input file
csv_file.close()
except FileNotFoundError:
print("File doesn't exist.")
exit()
谢谢!
【问题讨论】:
标签: python-3.x