【问题标题】:Check whether an element is there or not in a list using recursion in python [duplicate]使用python中的递归检查列表中是否存在元素[重复]
【发布时间】:2018-08-19 02:55:27
【问题描述】:

这是我为使用 Python 中的递归检查列表中是否存在元素而编写的代码。根据程序的流程,它应该返回 True,而是返回 None。请帮助解释我哪里出错了。提前致谢。

def numCheck(list,num):
    if len(list) == 0:
        return
    if list[0] == num:
        return True
    else:
        numCheck(list[1:],num)
print(numCheck([1,2,3],2))

【问题讨论】:

    标签: python arrays list recursion


    【解决方案1】:

    需要返回函数调用的结果:

    def numCheck(list,num):
      if len(list) == 0:
        return False
      if list[0] == num:
        return True
      return numCheck(list[1:],num)
    
    print(numCheck([1,2,3],2))
    

    输出:

    True
    

    【讨论】:

    • @Vedant 很高兴为您提供帮助!
    猜你喜欢
    • 2015-10-06
    • 2015-03-20
    • 1970-01-01
    • 2021-03-10
    • 2021-12-17
    • 2011-06-03
    • 2020-06-25
    • 2019-03-12
    • 2011-06-15
    相关资源
    最近更新 更多