【问题标题】:Using strings that represent instance variable in a python class to grab the value在 python 类中使用表示实例变量的字符串来获取值
【发布时间】: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


【解决方案1】:

您正在寻找类似的东西吗?

>>> things = [Thing([1,2,3]), Thing([4,5,6]), Thing([1,4,3])]
>>> things[0].__dict__
{'c': 3, 'a': 1, 'b': 2}
>>> for t in things:
    for att in t.__dict__:
        getattr(t, att)

输出是:

3
1
2
6
4
5
3
1
4

添加,只是为了完全清楚(我确实理解你的意思吗?你想要存储在 Thing 对象属性中的值的直方图?) 你可以这样做

hist = []
for t in things:
    for att in t.__dict__:
        hist.append(getattr(t, att))

然后不要打扰自己使用numpy:

import numpy as np
hist = np.hist(hist, bins=5)
>>> hist
(array([2, 1, 2, 2, 2]), array([ 1.,  2.,  3.,  4.,  5.,  6.]))

第一个数组是 bin 高度,第二个是 bin 值。或者你可以直接在 matplotlib.pyplot hist 函数中绘制它。

【讨论】:

    【解决方案2】:

    我很难理解你在寻找什么,但你说你可以在 ruby​​ 中很容易地做到这一点。这是相同的代码,但在 python 中:

    import csv
    from collections import defaultdict
    
    with open('trainingdatatostudents.csv') as openfile:
        reader = csv.reader(openfile)
        headers = reader.readline()
        records = []
        for i in range(10):
            hist = defaultdict(lambda: 0)
            for line in reader:
                records.append(line[i])
                hist[records[i]] += 1
            print hist
    

    这直接从 csv 中提取。不知道你要去哪里获取这些信息。

    【讨论】:

      【解决方案3】:
      import csv
      
      def hasNumbers(inputString):
          return any(char.isdigit() for char in inputString)
      
      class Student(object):
          def __init__(self, line):
              self.line = line
              self.id = line[0]
              self.ct = line[1]
              self.ucsz = line[2]
              self.ucsh = line[3]
              self.ma = line[4]
              self.sec = line[5]
              self.bn = line[6]
              self.bc = line[7]
              self.nn = line[8]
              self.m = line[9]
              self.ok = line[10]
      
          def __str__(self):
              return "id: " + str(self.id) + ", ct: " + str(self.ct) + ", ucsz: " + str(self.ucsz) + ", ucsh: " + str(self.ucsh) + ", ma: " + str(self.ma) + ", sec: " + str(self.sec) + ", bn: " + str(self.bn) + ", bc: " + str(self.bc) + ", nn: " + str(self.nn) + ", m: " + str(self.m) + ", ok: " + str(self.ok)
      
      x = []
      pp = ""
      with open('desk/trainingdatatostudents.csv') as f:
          flag = False
          reader = csv.reader(f)
          for row in reader:
              if flag is False:
                  pp = row
                  flag = True
              else:
                  x.append(Student(row))
      print pp
      q = []
      count = 1
      for val in range(1,11):
          hist = dict()   
          for s in x:
              if hasNumbers(s.line[val]) and int(s.line[val]) not in hist.keys():
                  hist[int(s.line[val])] = 0
              elif hasNumbers(s.line[val]):
                  hist[int(s.line[val])] += 1 
          print(pp[count] + str(hist))
          count = count + 1
      

      这段代码做我想做的事,只是想分享。我刚决定给我的学生一个数组实例变量,它让我的生活更轻松。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-28
        • 1970-01-01
        • 2017-08-08
        • 1970-01-01
        • 1970-01-01
        • 2021-03-28
        相关资源
        最近更新 更多