0

クラスで for ループを約 5 分間学習したところ、すでにラボが与えられていました。私は努力していますが、まだ必要なものを手に入れていません。私がやろうとしているのは、整数のリストを取得し、奇数の整数のみを取得してそれらを合計してから返すことです。整数のリストが [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 に答える