2012-03-05 30 views
0

我想弄清楚如何获取数字列表并将它们分类到某些类别,例如0-10,10-20,20-30和最多90 -100,但是我已经启动了代码,但是代码并未在所有输入中读取,而是只读取最后一个并重复它。我很难过,有人帮忙吗?如何将数字列表分组到某些类别

def eScores(Scores): 

    count0 = 0 
    count10 = 0 
    count20 = 0 
    count30 = 0 
    count40 = 0 
    count50 = 0 
    count60 = 0 
    count70 = 0 
    count80 = 0 
    count90 = 0 

    if Scores > 90: 
     count90 = count90 + 1 
    if Scores > 80: 
     count80 = count80 + 1 
    if Scores > 70: 
     count70 = count70 + 1 
    if Scores > 60: 
     count60 = count60 + 1 
    if Scores > 50: 
     count50 = count50 + 1 
    if Scores > 40: 
     count40 = count40 + 1 
    if Scores > 30: 
     count30 = count30 + 1 
    if Scores > 20: 
     count20 = count20 + 1 
    if Scores > 10: 
     count10 = count10 + 1 
    if Scores <= 10: 
     count0 = count0 + 1 

    print count90,'had a score of (90 - 100]' 
    print count80,'had a score of (80 - 90]' 
    print count70,'had a score of (70 - 80]' 
    print count60,'had a score of (60 - 70]' 
    print count50,'had a score of (50 - 60]' 
    print count40,'had a score of (40 - 50]' 
    print count30,'had a score of (30 - 40]' 
    print count20,'had a score of (20 - 30]' 
    print count10,'had a score of (10 - 20]' 
    print count0,'had a score of (0 - 10]'  

    return eScores(Scores) 
+0

一个更好的办法是使用一个数组来存储计数,然后只除以10号,查看桶它属于中...... – mpen 2012-03-05 05:34:53

+0

我的代码将返回这个“类型错误:eScores( )只需要1个参数(给出3个)“。是的,我是python的新手,任何人都可以指引我朝着正确的方向发展,为什么会发生这种情况,并且可能会在代码中强调这一点,谢谢。 – user1249113 2012-03-05 05:35:13

+1

@ user1249113:您所说的“TypeError”不是您显示的代码的结果。你如何调用函数? – 2012-03-05 05:41:49

回答

1

每次eScores被称为是将所有的计数器(count10count20)回到零。所以只有最后的通话才会有效果。

您应该将计数器声明为全局变量,或者将该函数放入类中并使该类的计数器成员变量。

的另一个问题是,函数调用自身的return声明:

return eScores(Scores) 

由于此功能是(我的理解)应该更新计数器变量而已,它并不需要任何回报,更不用说以递归方式调用它自己了。您最好删除return声明。

0

你犯错的一件事是,当你经历的时候,你并没有突破整套if。例如,如果你的数字是93,它将把count90设置为1,然后继续计数80并将其设置为1,等等,直到数到10。

+0

现在我明白了。我怎么能突破这一点,而不是让它发生?就是想。 – user1249113 2012-03-05 06:00:02

+0

我的意思是最简单的方法是什么。 – user1249113 2012-03-05 06:00:58

+0

不要只是继续使用'if',而应该使用'elif' – Vernon 2012-03-05 18:59:30

0

您的代码正在重复,因为该函数是无限递归的(它没有停止条件)。以下是相关位:

def eScores(Scores): 
    # ... 
    return eScores(Scores) 

我想你会希望更像是:

def eScores(Scores): 
    # same as before, but change the last line: 
    return 

因为你打印的结果,我想你不想返回值score10,score20

另外,函数不会累积结果,因为每次调用该函数时都会创建新的本地计数。

0

为什么你不使用每个数字作为一个键(处理后)并返回值的字典?

def eScores(Scores): 
    return_dict = {} 
    for score in Scores: 
     keyval = int(score/10)*10 # py3k automatically does float division 
     if keyval not in return_dict: 
      return_dict[keyval] = 1 
     else: 
      return_dict[keyval] += 1 
    return return_dict 
相关问题