尝试在字典中查找多个值的平均值 [英] Trying to find the average of multiple values in a dictionary
问题描述
我已经设法抓住每个键的所有值的总和,但我不确定如何找到这些新值的平均值。
import os
f = open(iris。数据,r)
count = 0
d = {}
#您希望字典具有d = {Iris-setosa:值列表]
#填充字典
#代码将工作,无论文件
#参考电影名称文件
在f中的行
如果line.isspace():
继续#如果一个特定的行是由空格组成的,忽略它
strip = line.strip(\\\
)#Strips out该特定的字符串
data = strip.split(,)
name = data [4]
如果d中的名称:
对于范围内的i(len(数据)-1):
d [name] [i] + = float(data [i])
d [name] [4] + = 1 #increment count
count + = 1
else:
d [name] = [float(i)因为我在da ta [0:4]]
d [name] .append(1)#keep count
count = 1
print(d)
f.close
您已经存储了每个值列表的计数;只需循环使用字典项目(键值)对,并使用值列表的最后一个元素:
for key,d.items()中的值:
avg = [v / values [-1] for v in values [: - 1]]
print(key,* avg)
这使用每个值的最后一个元素
列表作为行计数,并使用列表解析来生成每列的平均值。
其他一些备注:
-
你显然有一个CSV文件;请考虑使用
csv
模块而不是 -
你永远不会调用
f.close()
你只是引用它。
但是,您应该考虑将文件对象用作上下文管理器。
with
statement 确保该文件在您退出该文件时关闭:with open(iris.data,r )作为f:
在f中的行
line = line.rstrip('\\\
')
如果不是行:
继续
New to python here. Trying to get find the average of totaled up keys in a dictionary.
I've managed to grab the total of all values for each key, but I'm not certain how to find the average of these new values.
import os
f = open("iris.data", "r")
count = 0
d = {}
# You want the dictionary to have d = {Iris-setosa: list of values]
# Populate dictionary
# Code would work regardless of file
# Reference movie names file
for line in f:
if line.isspace():
continue #If a particular line is made of just spaces, ignore it
strip = line.strip("\n") #Strips out that particular string
data = strip.split(",")
name = data[4]
if name in d:
for i in range(len(data)-1):
d[name][i] += float(data[i])
d[name][4] += 1 #increment count
count += 1
else:
d[name] = [float(i) for i in data[0:4]]
d[name].append(1) #keep count
count = 1
print(d)
f.close
You already store a count with each list of values; simply loop over the dictionary items (key-value) pairs and use the last element of the value lists:
for key, values in d.items():
avg = [v / values[-1] for v in values[:-1]]
print(key, *avg)
This uses the last element of each values
list as the row count, and uses a list comprehension to produce an average value for each of your columns.
Some other remarks:
you evidently have a CSV file; consider using the
csv
module instead.you never called the
f.close()
method; you merely referenced it.However, you should consider using the file object as a context manager instead. The
with
statement ensures that the file is closed for you when the block is exited:with open("iris.data", "r") as f: for line in f: line = line.rstrip('\n') if not line: continue
这篇关于尝试在字典中查找多个值的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!