【问题标题】:Every Items Length in PythonPython中的每个项目长度
【发布时间】:2013-01-19 19:13:17
【问题描述】:

我试图定义一个函数,如果列表中的每个项目都小于 2,则返回 true,否则返回 false。项目的类型可以是与列表不同的整数、浮点数、str 或某物。我应该检查清单。

def ifeveryitems(lst):
    for items in lst:
        if isinstance(items,list) and len(items) <= 2:
           return True and ifeveryitem(????)  # '????' should be the items other than the item that has been searched #
        else:
           return False

【问题讨论】:

    标签: python search


    【解决方案1】:

    从你的描述来看,你根本不需要递归调用:

    def ifeveryitems(lst):
        for items in lst:
            if isinstance(items, list) and len(items) > 2:
               return False
    
        return True
    

    或者,或者:

    def ifeveryitems(lst):
        return all(len(items) <= 2 for items in lst if isinstance(items, list))
    

    【讨论】:

    • 非常感谢!这正是我正在寻找的!
    • all(len(items) &lt;= 2 for items in lists if isinstance(items, list)) 可能更具可读性
    【解决方案2】:

    您可以尝试以下方法:

    def ifeveryitems(lst):
        return all(map(lambda x: x < 2, lst)) 
    

    【讨论】:

    • 问题是“我试图定义一个函数,如果列表中的每个项目都小于 2,则返回 true,否则返回 false。”我认为这个解决方案符合这个要求,尽管我可能误解了它的意思。如果“小于 2”意味着“是一个少于两个元素的列表”,则它不起作用
    • 啊,对不起,我不小心把代码和问题结合起来了:P
    【解决方案3】:

    解决了您的问题后,我将一般解释循环与尾递归的概念,因为尾递归通常是一种有用的技术。
    尽管 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]) &lt;= 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。

    【讨论】:

    • Python 没有尾调用消除,因此尾递归解决方案很少有用。你在ifeveryitems() 中忘记了return。由于1 +,您的len() 不是尾递归的,请尝试以下操作:size = lambda L, total=0: size(L[1:], total + 1) if L else total
    • 查看the pictures in SICP 以了解为什么您的len()return 1+len() 不是尾递归的。 len() 调用不在尾部,add 运算符在尾部位置:return add(1, len()),将其与 size() 函数进行比较(您可以将其重写为多行 def 以区别于len()显式)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    相关资源
    最近更新 更多