【问题标题】:Python - len function not working as expected, and giving me the error "TypeError: object of type 'int' has no len()"Python - len 函数没有按预期工作,并给我错误 \"TypeError: object of type \'int\' has no len()\"
【发布时间】:2022-09-23 16:40:38
【问题描述】:

在研究来自 - https://composingprograms.com/pages/23-sequences.html#linked-lists 的链表时

empty =\'empty\'
four = [1, [2, [3, [4, \'empty\']]]]
x = [1,2];

def is_link(s):
    \"\"\"s is a linked list if it is empty or a (first, rest) pair.\"\"\"
    return s == empty or (len(s) == 2 and is_link(s[1]))

print(is_link(four))
print(is_link(x))

该程序将四个识别为链表,但是当我插入 x 时,它返回错误而不是返回 \"False\"。

如果我将 x 的值更改为仅 [1] 或 [1,2,3] 它会按预期返回,但是如果我输入具有 2 个值的普通列表 [1,2] 我会遇到此错误。 。为什么是这样?

  • 它适用于[1][1, 2, 3],因为len(s) == 2 条件失败并返回False。对于[1, 2] - 长度为2,但最后一个元素是int,它没有len
  • 如果您在is_link 的开头添加print(s),应该很容易找出问题所在。
  • @Mortz我认为您的回答是正确的逻辑。

标签: python function


【解决方案1】:

问题出在这部分:

is_link(s[1])

s[1] 是 int 因此它没有 len() 方法。您需要检查方法 is_link 中的参数是否是这样的列表

return type(s) == list and (s == empty or (len(s) == 2 and is_link(s[1])))

【讨论】:

  • 我没有对你投反对票,但如果你说的是真的,让我们说 s =[1,2,3] 也应该返回错误,但它返回正确的答案
猜你喜欢
  • 2020-08-25
  • 2021-10-05
  • 2020-04-23
  • 2015-01-20
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
相关资源
最近更新 更多