我想:
课程有效,代码有效,频率表正确
我想得到一个返回字典的类,但实际上我得到了一个返回类类型的类
我可以看到里面有正确的内容,但我就是拿不出来
有人能告诉我如何将类的输出转换为字典类型吗
我正在与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
变成真正的字典
类不能返回东西——类中的函数可以。但是,类中的函数没有;它只是修改
self.dict_name
(这是一个用词不当的词;它实际上只是对dict的引用,而不是一个名称(人们可能会认为它是一个字符串)),调用者然后读取(或者无论如何应该读取)此外,似乎还有一个bug;第二个
if
块(无论如何都不会到达)引用了row
,这是一个未定义的名称无论如何,您的类根本不需要是类,并且最容易通过内置的
collections.Counter()
类实现:如果希望
make_table
函数返回字典,则必须在其末尾添加return
语句,例如:return self.dict_name
如果你想在类之外使用它,你必须把它赋给一个变量,所以在第二个截取的do:
my_dict = pph.make_table()
相关问题 更多 >
编程相关推荐