Python降序列表

时间:2016-08-15 16:21:35

标签: python python-2.7 python-3.x

如果函数中的列表输入不是降序,我想创建一个返回false的函数,

现在为降序([19,17,18,7]),它返回true

我不知道为什么出于某种原因它会退出if语句并且每次打印都是真的。

def des(l):
    for i in range(len(l)):
            if (l[i]<l[i+1]):
                return [False,i]
            else:
                return True

4 个答案:

答案 0 :(得分:1)

这是编写函数的另一种方法:

def des(l):
    return all(i>j for i,j in zip(l,l[1:]))

答案 1 :(得分:1)

问题是您只进行一次检查,并且立即返回TrueFalse

相反,在检查完整个列表之前,你不应该返回“True”:

def des(l):
    for i in range(len(l)):
        if (l[i]<l[i+1]):
            return [False,i]
    return True

但这会给你带来另一个问题:

>>> des([4,3,2,1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in des
IndexError: list index out of range

这是因为当您到达range中的最后一个值时,您会看到超出列表末尾的值。解决这个问题的最简单方法是从你的范围中减去一个:

def des(l):
    for i in range(len(l) - 1):
        if (l[i]<l[i+1]):
            return [False,i]
    return True

在python中,使用range(len(...))通常是不好的做法。一个更好的选项是enumerate,它会返回一对(index, value)对,但这并不能解决上述问题:

def des(l):
    for i, v in enumerate(l):
        if (v < l[i+1]):
            return [False,i]
    return True

这仍然存在IndexOutOfRange错误。我们可以通过假装列表来解决这个问题,我们将重复一遍:

def des(l):
    for i, v in enumerate(l[:-1]):
        if (v < l[i+1]):
            return [False,i]
    return True

你有更多的&#34; pythonic&#34; (即以python专家的风格)解决方案。

此代码还有另外一个unpythonic问题:如果你执行if des(my_list)): ...,它就无法工作。这是因为非空list(您在return语句中使用[]创建的内容总是真实。

如果你想获得升序项目的索引,那么实际上没有任何方法,但应该在函数名称中更清楚。

另外,你不能

is_descending, bad_index = des(...)

因为您只是在成功时返回True。更好的是

def des(l):
    for i, v in enumerate(l[:-1]):
        if (v < l[i+1]):
            return (False,i)
    return (True, None)

另请注意,我使用括号对结果对进行分组,这会创建一个新的tuple。一般情况下,如果所有成员代表相同的事情,则应使用list,如果成员代表不同的事物,则应使用tuple ,例如在这种情况下,它们代表结果,以及发生故障的

答案 2 :(得分:0)

试试这个:

def des(l):
    for x in l:
        try:
            if x < l[l.index(x)+1 ]-1:
                return True
        except:
            pass
    return False

答案 3 :(得分:0)

def des(l):
    for i in range(len(l)):
        if (l[i]<l[i+1]):
            return [False,i]

    return True

如果非假,则返回True。只有在整个for循环运行时才返回true。因此它必须在for循环之外。如果循环一直运行并且没有返回任何内容,则返回True