TypeError: cannot unpack non-iterable int object, Plus Minus problem in HackerRank

TypeError: cannot unpack non-iterable int object, Plus Minus problem in HackerRank

我不知道如何解决这个问题,尝试在 vscode 和 hackerrank IDE 上执行它,尽管网络上的所有解决方案都与我的相同,但两者都出现错误

import math
import os
import random
import re
import sys

#
# Complete the 'plusMinus' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#

def plusMinus(arr):
    # Write your code here
    neg,pos,zero=0
    for i in range(0,len(arr)):
        if(arr[i]<0):
            neg+=0
        elif(arr[i]>0):
            pos+=0
        else:
            zero+=0
    print(pos/len(arr))
    print(neg/len(arr))
    print(zero/len(arr))
    return 0
if __name__ == '__main__':
    n = int(input().strip())

    arr = list(map(int, input().rstrip().split()))

    plusMinus(arr)
Traceback (most recent call last):
  File "/tmp/submission/20211128/06/29/hackerrank-a7793862d075fcff390bb368bc113c47/code/Solution.py", line 35, in <module>
    plusMinus(arr)
  File "/tmp/submission/20211128/06/29/hackerrank-a7793862d075fcff390bb368bc113c47/code/Solution.py", line 17, in plusMinus
    neg,pos,zero=0
TypeError: cannot unpack non-iterable int object  

阅读回溯揭示了您遇到的错误的原因:

Traceback (most recent call last):
  File "/tmp/submission/20211128/06/29/hackerrank-a7793862d075fcff390bb368bc113c47/code/Solution.py", line 35, in <module>
    plusMinus(arr)
  File "/tmp/submission/20211128/06/29/hackerrank-a7793862d075fcff390bb368bc113c47/code/Solution.py", line 17, in plusMinus
    neg,pos,zero=0
TypeError: cannot unpack non-iterable int object  

正确的语法是

# map the elements of the iterable on the right-hand side to the 
# declared variable names
neg, pos, zero = 0, 0, 0

# assign the same value to all declared variables
neg = pos = zero = 0 

正如所写,它试图将整数 0 解压缩为三个单独的值 neg, pos, zero。由于 0 不是像元组那样的可迭代对象(例如,0, 0, 0 是),因此不能解压缩为多个值,因此 python 会抛出错误。