【发布时间】:2015-02-19 22:51:42
【问题描述】:
class Thing(object):
def __init__(self, array):
self.a = array[0]
self.b = array[1]
self.c = array[2]
我有一个 Thing 对象列表,每个对象都有一组值。我正在尝试计算包含在 a、b、c 中的值的频率分布的直方图,因此我有一个基本上可以执行的脚本:
hist = dict()
for t in things:
if t.a not in hist.keys():
hist[s.a] = 0
else:
hist[s.a] += 1
但是,我希望能够概括代码,以便我有一个本地字典来存储 a 的频率,然后是 b 的频率。我可以通过读取 CSV 文件在 ruby 中非常轻松地做到这一点(这是 Thing 属性的来源,我创建了一个类,因为我在过去创建不适合后续更改的脚本时遇到了问题,因为它们是如此临时。
f = File.open('trainingdatatostudents.csv')
lines = f.readlines
attributes = lines[0]
attributes = attributes.split(",")
records = []
1.upto(10).each {|num|
hist = Hash.new(0)
name = ""
lines.each {|line|
elements = line.split(",")
records.push(elements[num])
hist[elements[num]] += 1
}
puts hist
}
我知道我可以使用类的每个实例中的 dict 变量,但我只是将值作为字符串,我不能做类似 s 的事情。"a “那我该怎么做呢?
谢谢
【问题讨论】:
-
输入文件和预期输出示例?
标签: python instance-variables accessor