python中“int类型的对象没有长度”是什么意思?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (827)

我试着在Windows 10上用Python3.6.5编写一个程序,该程序将接受整数,然后打印出奇怪的。

def listInput():
    aList = list()
    while True:
        num = input("Please input a number:")
        if num == 'done':
            break
        num = int(num)
        aList.append(num)
    return aList

def isOddNumber(y):
    if y%2 == 0:
        return False
    else:
        return True

def filterOddInList(a):
    i = len(a)
    while i >= 0:
        item = a[(i-1)]
        odd = filterOddInList(item)
        if odd == False:
            x.pop()

def main():
    a = listInput()
    print(a)
    a = filterOddInList(a)
    print(a)

main()

这是应该发生的事:

Please input a number:1
Please input a number:2
Please input a number:3
Please input a number:4
Please input a number:5
Please input a number:done
[1, 2, 3, 4, 5]
[1, 3, 5]

这就是实际发生的事情:

Please input a number:1
Please input a number:2
Please input a number:3
Please input a number:4
Please input a number:5
Please input a number:done
[1, 2, 3, 4, 5]
Traceback (most recent call last):
  File "C:\Users\Jerry Cui\Documents\New folder\Homework\oddonly.py", line         30, in <module>
    main()
  File "C:\Users\Jerry Cui\Documents\New folder\Homework\oddonly.py", line 27, in main
    a = filterOddInList(a)
  File "C:\Users\Jerry Cui\Documents\New folder\Homework\oddonly.py", line 20, in filterOddInList
    odd = filterOddInList(item)
  File "C:\Users\Jerry Cui\Documents\New folder\Homework\oddonly.py", line 17, in filterOddInList
    i = len(a)
TypeError: object of type 'int' has no len()

有人能告诉我为什么会发生这个错误吗?正确的代码应该是什么?

提问于
用户回答回答于
def filterOddInList(a):
  i = len(a)
  x = a
  while i >= 0:
    item = a[(i-1)]
    odd = isOddNumber(item)
    if odd == False:
        x.remove(item)
    i -= 1
  return x
用户回答回答于

问题在于FilterOddInList内部的递归。你用“Item”来称呼它,这是一个数字。当你到达len(A)时,它试图提取一个数字的连字符,但失败了。

扫码关注云+社区

领取腾讯云代金券