TypeError:尽管正确使用了range函数,但“int”对象不可iterable

2024-05-19 17:38:19 发布

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

我正在写一个来自Hackerrank的代码,代码如下

def miniMaxSum(arr):
    minsum,maxsum=0
    arr.sort()
    for i in range(4):
        minsum+=arr[i]
    print(minsum)
    for j in range(1,5):
        maxsum+=arr[i]
    print(maxsum)


if __name__ == '__main__':
    arr = list(map(int, input().rstrip().split()))

    miniMaxSum(arr)

我们应该从五个元素中的四个元素中找出最小和和最大和 但它给了我以下的错误

Traceback (most recent call last):
  File "solution.py", line 24, in <module>
    miniMaxSum(arr)
  File "solution.py", line 11, in miniMaxSum
    minsum,maxsum=0
TypeError: 'int' object is not iterable

我使用范围函数正确,但我得到的错误。你知道吗


Tags: 代码inpy元素for错误rangefile
1条回答
网友
1楼 · 发布于 2024-05-19 17:38:19

您可以通过执行minsum, maxsum = 0得到这个错误的原因。 您必须使用序列(例如list、tuple、dict或range)。Python将对其进行迭代,然后将相应的值赋给变量。当然,左侧和右侧的元素数必须相同。如果只有一个,那就是一个序列。你知道吗

正如评论所说,您可以执行minsum, maxsum = 0, 0。你知道吗

当然,不涉及Range()。你知道吗

除此之外,您还可以执行以下操作:

for value in arr[:4]:
    minsum += value
for value in arr[1:]:
    maxsum += value

它比使用范围和索引更好。我建议您按照PEP8推荐的函数名(mini_max_sum而不是miniMaxSumPEP8 function and variable names

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

相关问题 更多 >