为什么我得到TypeError:“int”对象不可编辑

2024-09-27 00:13:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我运行这段代码是为了找到偶数之和。 这是我的密码

from functools import reduce

liste = [1,2,3,4,5,6,7,8,9,10]

def cift_mi(a):
    if (a % 2 == 0):
        return True
    return False

ciftler = (list(filter(cift_mi,liste)))

def toplama(a,b):
    return a + b

sonuc=(list(reduce(toplama,list(ciftler))))

print(sonuc)

运行代码时,我收到以下错误:

TypeError: 'int' object is not iterable

Tags: 代码from密码reducereturndeflist偶数
1条回答
网友
1楼 · 发布于 2024-09-27 00:13:29

要了解这一点,请查看错误发生在哪一行:

Traceback (most recent call last):
  File "main.py", line 15, in <module>
    sonuc=(list(reduce(toplama,list(ciftler))))
TypeError: 'int' object is not iterable

它显示了发生错误的行,但该行发生了几件事,因此我们可以将其分解为单独的部分:

ciftler_list = list(ciftler)
reduced_value = reduce(toplama, ciftler_list)
sonuc = list(reduced_value)

现在错误发生了变化:

Traceback (most recent call last):
  File "main.py", line 18, in <module>
    sonuc = list(reduced_value)
TypeError: 'int' object is not iterable

错误是说list正在尝试迭代一个值,但该值是一个int,因此它不能。这意味着reduced_value必须是一个int。因此,reduce函数必须返回一个int

这是有意义的,因为reduce函数toplama返回a + b,所以reduce将返回ciftler中所有值的总和。它的返回值是一个int,而不是一个list,因此不能对它调用list()

您可能希望任务如下所示:

# ciftler is already a list, don't need to call list() again
sonuc = reduce(toplama, ciftler)

相关问题 更多 >

    热门问题