【问题标题】:Easy python program简单的python程序
【发布时间】:2012-04-12 17:57:30
【问题描述】:

提示用户输入文件,在本例中为“histogram.txt”。该程序获取文本文件中的每个分数,并从文件中的所有等级中制作一个直方图,将它们组织起来,以便用户可以看到每个范围有多少。我写了一个很简单的代码:

filename = raw_input('Enter filename of grades: ')

histogram10 = 0
histogram9 = 0
histogram8 = 0
histogram7 = 0
histogram6 = 0
histogram5 = 0
histogram4 = 0
histogram3 = 0
histogram2 = 0
histogram1 = 0
histogram0 = 0

for score in open(filename):
    if score >= 100:
        histogram10 = histogram10 + 1
    elif score >= 90: 
        histogram9 = histogram9 + 1
    elif score >= 80:
        histogram8 = histogram8 + 1
    elif score >= 70:
        histogram7 = histogram7 + 1
    elif score >= 60:
        histogram6 = histogram6 + 1
    elif score >= 50:
        histogram5 = histogram5 + 1
    elif score >= 40:
        histogram4 = histogram4 + 1
    elif score >= 30:
        histogram3 = histogram3 + 1
    elif score >= 20:
        histogram2 = histogram2 + 1
    elif score >= 10:
        histogram1 = histogram1 + 1
    elif score >= 0:
        histogram0 = histogram0 + 1

print    
print 'Grade Distribution'
print '------------------'
print '100     :',('*' * histogram10)
print '90 - 99 :',('*' * histogram9)
print '80 - 89 :',('*' * histogram8)
print '70 - 79 :',('*' * histogram7)
print '60 - 69 :',('*' * histogram6)
print '50 - 59 :',('*' * histogram5)
print '40 - 49 :',('*' * histogram4)
print '30 - 39 :',('*' * histogram3)
print '20 - 29 :',('*' * histogram2)
print '10 - 19 :',('*' * histogram1)
print '00 - 09 :',('*' * histogram0)

但是,每当我运行该程序时,所有 20 个成绩都会记录到 >= 100 像这样:

100    : ********************
90-99  : 
80-89  : 

等等。 ...我如何才能让程序将星星放在正确的位置?

【问题讨论】:

  • 总是第 1 步:确保进入程序的数据是正确的。
  • 您正在将字符串与数字进行比较...
  • 一个小提示:您可以使用一个列表并计算索引,而不是为直方图设置 11 个不同的变量,例如histogram[min(100, score) / 10] += 1min 是将所有高于 100 的分数放在同一个插槽中。对于更一般的数据,例如计算文本中的单词数,您可以使用字典。
  • 一个班轮只是为了好玩any(__import__('sys').stdout.write('<= {} \t {}\n'.format(i * 10 + 10, '*' * num)) for i, num in ((k, len(list(g))) for k, g in __import__('itertools').groupby( sorted(int(score.strip()) for score in open(raw_input('Enter filename of grades: '))), key = lambda score: (score - 1) / 10)))

标签: python


【解决方案1】:

您需要在比较之前将score 转换为int。

score = int(score)  # convert to int
if score >= 100:
    histogram10 = histogram10 + 1
# other cases

如果输入文件中有空行,则必须在转换为 int 之前添加必要的检查。此外,您可以轻松地使用列表来代替十个不同的变量。

【讨论】:

  • 谢谢你,我也很感激你的建议。我在 compsci 还是很新的 :P 如果你不介意你能解释一下如何使用这个列表吗?
  • 请浏览列表教程docs.python.org/tutorial/introduction.html#lists。对于histogram0,你可以使用l[0],对于histogram1,你可以使用l[1]等等。
【解决方案2】:

从文件中读取的数据是一个字符串。首先将其转换为整数,将其传递给int()

>>> int('25')
25

【讨论】:

    猜你喜欢
    • 2015-12-20
    • 2014-05-10
    • 2012-08-10
    • 2015-03-30
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    相关资源
    最近更新 更多