从课堂上得到一本字典?

2024-06-10 03:36:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想:

  1. 拿一张清单
  2. 在字典里做一个频率表
  3. 使用生成的字典进行操作

课程有效,代码有效,频率表正确

我想得到一个返回字典的类,但实际上我得到了一个返回类类型的类

我可以看到里面有正确的内容,但我就是拿不出来

有人能告诉我如何将类的输出转换为字典类型吗

我正在与HN post data合作。列,数千行

freq_pph = {}
freq_cph = {}
freq_uph = {}

# Creates a binned frequency table:
# - key is bin_minutes (size of bin in minutes).
# - value is freq_value which sums/counts the number of things in that column. 
class BinFreq:
  def __init__(self, dataset, bin_minutes, freq_value, dict_name):
    self.dataset = dataset
    self.bin_minutes = bin_minutes
    self.freq_value = freq_value
    self.dict_name = dict_name

  def make_table(self):
    # Sets bin size
    # Counts how of posts in that timedelta
    if (self.bin_minutes == 60) and (self.freq_value == "None"):
      for post in self.dataset:
        hour_dt = post[-1]
        hour_str = hour_dt.strftime("%H")
        if hour_str in self.dict_name:
           self.dict_name[hour_str] += 1
        else:
           self.dict_name[hour_str] = 1
    # Sets bins size
    # Sums the values of a given index/column
    if (self.bin_minutes == 60) and (self.freq_value != "None"):
      for post in self.dataset:
        hour_dt = post[-1]
        hour_str = hour_dt.strftime("%H")
        if hour_str in self.dict_name:
          self.dict_name[hour_str] += int(row[self.freq_value])
        else:
          self.dict_name[hour_str] = int(row[self.freq_value])

举例说明:

pph = BinFreq(ask_posts, 60, "None", freq_pph)
pph.make_table()

怎样才能把pph变成真正的字典


Tags: ofnameinself字典binvaluepost
2条回答

类不能返回东西——类中的函数可以。但是,类中的函数没有;它只是修改self.dict_name(这是一个用词不当的词;它实际上只是对dict的引用,而不是一个名称(人们可能会认为它是一个字符串)),调用者然后读取(或者无论如何应该读取)

此外,似乎还有一个bug;第二个if块(无论如何都不会到达)引用了row,这是一个未定义的名称

无论如何,您的类根本不需要是类,并且最容易通过内置的collections.Counter()类实现:

from collections import Counter


def bin_by_hour(dataset, value_key=None):
    counter = Counter()
    for post in dataset:
        hour = post[-1].hour  # assuming it's a `datetime` object
        if value_key:  # count using `post[value_key]`
            counter[hour] += post[value_key]
        else:  # just count
            counter[hour] += 1
    return dict(counter.items())  # make the Counter a regular dict


freq_pph = bin_by_hour(ask_posts)
freq_cph = bin_by_hour(ask_posts, value_key="num_comments")  # or whatever

如果希望make_table函数返回字典,则必须在其末尾添加return语句,例如:return self.dict_name

如果你想在类之外使用它,你必须把它赋给一个变量,所以在第二个截取的do:my_dict = pph.make_table()

相关问题 更多 >