【问题标题】:TypeError-'function' object is not iterableTypeError-'function' 对象不可迭代
【发布时间】:2016-07-31 16:01:17
【问题描述】:

我有一个程序,教师可以查看她学生的测验结果并以一种简单的方式对其进行排序:

if role == 2:
class_number = prompt_int_big("Which class' scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3")
filename = (str(class_number) + "txt")
sort_or_not = prompt_int_small("Would youlike to sort these scores in any way? Press 1 if the answer is no or 2 if the answer is yes")
if sort_or_not == 1:
    f = open(filename, "r")
    lines = [line for line in f if line.strip()]
    lines.sort()
    for line in lines:
        print (line)
if sort_or_not == 2:
    type_of_sort = prompt_int_big("How would you like to sort these scores? Press 1 for scores in alphabetical order with each student's highest score for the tests, 2 if you would like to see the students' highest scores sorted from highest to lowest and 3 if you like to see these student's average scores sorted from highest to lowest")
    if type_of_sort == 1:
        with open(filename , 'r') as r:
            for line in sorted(r):
                print(line, end='')
    if type_of_sort == 2:
        with open (filename,'r') as r:
            def score(line):
                return int(line.split(':')[1])
            for line in sorted(r, key=score, reverse = True):
                print(line)
    if type_of_sort == 3:
        with open (filename,'r') as r:
            def score(line):
                returnint(line.split(':')[1])
            average = sum(map(int, score))/len(score)
            print(name,"--",average)

However when the third option is selected an error comes up:

average = sum(map(int, score))/len(score)
TypeError-'function' object is not iterable

【问题讨论】:

  • 如果你要投反对票,至少说明原因
  • 投反对票的意思是,当用户投反对票时,来自 SO 的确切引用:“这个问题没有任何研究工作,不清楚或没有用”。在这种情况下,我最好的建议是:请花点时间阅读Help center 中的提问指南。

标签: python-3.x random average typeerror


【解决方案1】:

map() 在 Python-3.x 中返回一个迭代器(与 Python-2.x 不同,它返回结果列表)。因此,您需要从迭代器生成列表,然后将其传递给sum() 函数。

average = sum(list(map(int, score)))/len(score)

在上面,示例score 应该是可迭代的,就像一个列表或一个元组。

编辑:好吧,map 将 iterable 作为参数(如列表、元组),但在这种情况下,传递的参数 score 是一个函数。而且您正在传递函数名称而不是调用该函数。因此,一个函数被传递给map() 函数。因此,您需要调用该函数。例如:

score_list = score(r.readline())
average = sum(list(map(int, score_list)))/len(score_list)

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2013-09-01
    • 2017-08-27
    • 2018-10-10
    • 2021-12-13
    相关资源
    最近更新 更多