【问题标题】:Bad output when building a histogram构建直方图时输出错误
【发布时间】:2017-08-08 19:57:35
【问题描述】:

我在构建直方图时遇到了一些问题。

这是我的代码:

distribution = dict()
count = 0
name = input("Enter file:")
handle = open(name)
for line in handle:
    line = line.rstrip()
    if not line.startswith("From "):
        continue
    count = count + 1
    firstSplit = line.split()           # This gets me the line of text
    time = firstSplit[5]                # This gets me time - ex: 09:11:38
    # print(firstSplit[5])
    timeSplit = time.split(':')
    hr = timeSplit[1]                   # This gets me hrs - ex: 09

    # Gets me the histogram
    if hr not in distribution:
        distribution[hr[1]] = 1
    else:
        distribution[hr[1]] = distribution[hr[1]] + 1
    print(distribution)

# print(firstSplit[5])

我阅读了文本,然后将其拆分为行,由firstSplit 完成。这行文本包括一个时间戳。我进行第二次拆分以获得时间,由timeSplit 完成。

从这里开始,我尝试通过查看小时是否在字典中来构建直方图,如果是,则添加一个,如果不是,则添加小时。但这就是问题所在。我的输出看起来像:

Example of Output

任何建议或建议都会很棒!

肖恩

【问题讨论】:

  • 我至少发现了一个问题。我使用 hr[1] 作为索引,但它应该是 hr[0]。仍然得到不好的输出。
  • 我想我已经完成了这 90%,我只需要现在就安排我的工作时间。

标签: python-3.x dictionary histogram


【解决方案1】:

您使用了不正确的方法来检查小时是否是直方图中的键。以下是正确的检查方法:

if not (hr in list(distribution.keys()):

此外,您应该检查一个值是否是一个键,然后使用 same 值作为您创建/添加到的键。因此,以上内容现在将是:

if not (hr[1] in list(distribution.keys()):

这两项更改应该可以修复您的代码并为您构建一个出色的直方图!


注意: 代码未经测试

【讨论】:

    猜你喜欢
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多