随着您的问题解决,我w应该一般性地解释循环与尾递归的概念,因为尾递归通常是一种有用的技术。
尽管Python中的循环和列表理解意味着您不太可能需要尾递归,但有一个想法是很好的。
递归调用函数的技术称为尾递归。使用尾递归和循环可以达到同样的效果,但是你不需要两者。
,做你想做,你可以使用一个循环什么:
def ifeveryitems(lst):
for items in lst:
if not isinstance(items,list) or len(items) > 2:
return False
return True
或尾递归:
def ifeveryitems(lst):
if isinstance(items,list) and len(lst)==0:
return True
return isinstance(lst[0],list) and len(lst[0]) <= 2 and ifeveryitems(lst[1:])
此功能检查的lst
的第一个项目是列表,是一个长度为2或更少,然后使用函数本身检查列表的其余部分(lst[1:]
)。最终,它会通过快捷方式返回False(当isinstance(lst[0],list) and len(lst[0]) <= 2
为False时)或到达整个列表耗尽的基本情况,此时它将返回True。
再举一个例子:自己实现len(L)
。
假设L
将永远是一个列表,你可以使用一个循环实现len
:
def len(L):
i = 0
for item in L:
i += 1
return i
(注:使用这样的循环也被称为累积)
或尾递归。
def len(L):
if L==[]:
return 0
return 1 + len(l[1:])
它删除列表中的第一个项目,并将其余列表的长度加1。最终,它会达到L耗尽的地步,并被减少到空列表,在这种情况下,它将返回0.
非常感谢!这正是我正在寻找的! –
'如果isinstance(items,list))'all(len(items)<= 2)'可能更具可读性 – jfs
@ J.F.Sebastian:好点! – Ryan