0

我们刚刚在课堂上学习了大约五分钟的 for 循环,我们已经得到了一个实验室。我正在尝试但仍然没有得到我需要得到的东西。我想要做的是取一个整数列表,然后只取奇数并将它们相加然后返回它们,所以如果整数列表是 [3,2,4,7,2,4,1, 3,2] 返回值为 14

def f(ls):
    ct=0
    for x in (f(ls)):
        if x%2==1:
            ct+=x
    return(ct)


print(f[2,5,4,6,7,8,2])

错误代码读取

Traceback (most recent call last):
  File "C:/Users/Ian/Documents/Python/Labs/lab8.py", line 10, in <module>
    print(f[2,5,4,6,7,8,2])
TypeError: 'function' object is not subscriptable
4

2 回答 2

5

只是几个小错误:

def f(ls):
    ct = 0
    for x in ls:
    #       ^     Do not call the method, but just parse through the list  
        if x % 2 == 1:
            ct += x
    return(ct)
    #     ^  ^ parenthesis are not necessary 

print(f([2,5,4,6,7,8,2]))
#      ^               ^    Missing paranthesis
于 2013-04-05T15:36:50.647 回答
1

您在函数调用中缺少括号

print(f([2,5,4,6,7,8,2]))

而不是

print(f[2,5,4,6,7,8,2])
于 2013-04-05T15:36:55.827 回答