带有可变参数的 Python "maximum recursion depth exceeded in comparison"。但是,可以很好地处理列表

标签 python list python-3.x recursion tuples

我有以下功能:

def lst(*l):
  if l==():return None
  else: return cons(l[0],lst(l[1:]))

当我运行它时,我得到“相比之下超出了最大递归深度”。奇怪的是,当我添加一个将参数元组转换为列表的 warper 时,一切正常:

def lst(*l):
  return _lst(list(l))

def _lst(l):
  if l==[]:return None
  else: return (l[0],_lst(l[1:]))

>>> lst(1,2)
(1, (2, None))

问题是什么以及如何处理这种奇怪的行为?

最佳答案

再次将参数传递给函数时缺少*

def lst(*l):
  if l==():return None
  else: return cons(l[0],lst(*l[1:]))

您将空元组作为第一个位置参数传递,这意味着在下一个递归中 l 实际上等于 ((),)(一个元组包含一个空元组)应该是 ()

关于带有可变参数的 Python "maximum recursion depth exceeded in comparison"。但是,可以很好地处理列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23158000/

相关文章:

python - 获取语​​法错误: future feature google_type_annotations is not defined

python - 在 Windows 上安装 M2Crypto

python - 使用 FLask 和 matplotlib 即时生成图像

list - Scala:从列表中提取重复值

python - 如何仅取消堆栈 pandas 数据框列表中的列表?

python - 为什么扩展切片分配不如常规切片分配灵活?

python - 每个值多个键

Python打包: build requirements in pyproject. toml VS setup_requires

django:如何从右到左渲染 CharField?

python-3.x - 如何使用 python 3.2 安装 MySQLdb