你怎么知道你的列表在python中是否升序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19916143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:57:41  来源:igfitidea点击:

how do you know if your list is ascending in python

python

提问by user2980776

I wrote this program in python to see if a list is ascending and its not working, can someone help me?

我在 python 中编写了这个程序来查看列表是否在升序并且不起作用,有人可以帮助我吗?

list1 = [1, 2, 3, 4]
print (list1)
length = len(list1)
run_started = False
for x in range(length - 1):
    t = list1[x + 1] - list1[x]
    if t > 0 :
        if run_started:
            run_length = x
        else:
            run_started = True
            run_length = x
    else:
        if run_started:
            print (True)
            print ("Run Length: {0}".format(run_length))
            break
if not run_started:
    print (False)

回答by jbat100

I'd say the easiest (although not the most efficient) way would be:

我想说最简单(虽然不是最有效)的方法是:

list1 = [3, 1, 2, 4]

if sorted(list1) == list1:
    print "list1 is sorted"

回答by Alex Chumbley

I think the OP is asking what is wrong with their own code. If that's the case, here goes:

我认为 OP 是在问他们自己的代码有什么问题。如果是这种情况,请执行以下操作:

It looks like you never reach the end condition that you want. I mean, you get your run_startedvariable to get to True. But then what? Nothing else happens in your code since you never trigger the elsestatement that is contrary to your if t > 0statement. I think you should re-think the logic in your code and what you want it to do exactly

看起来你永远不会达到你想要的最终条件。我的意思是,你让你的run_started变量达到 True。但是然后呢?您的代码中不会发生任何其他事情,因为您从未触发else与您的if t > 0语句相反的语句。我认为您应该重新考虑代码中的逻辑以及您希望它完全做什么

EDIT:your code commented, I've put numbers in {{}} to show what happens in what order

编辑:您的代码已注释,我已将数字放入 {{}} 以显示发生的顺序

list1 = [1, 2, 3, 4]
print (list1)
length = len(list1)
run_started = False
for x in range(length - 1): # Loop begins {{1}}
    t = list1[x + 1] - list1[x]
    if t > 0 : 
        if run_started:
            run_length = x #You keep setting a new run_length {{3}}
        else:
            run_started = True #You've set run_started  {{2}}
            run_length = x
    else:
        if run_started:
            print (True)
            print ("Run Length: {0}".format(run_length))
            break
if not run_started: #Then this is called after the loop {{4}} but it doesn't return true
    print (False)

As you can see, you exit the for loop without ever calling else on line 13. Furthermore then final if not run_startedis also never called. Your code works the way it is designed to work, though maybe not the way you want it to work. HTH

正如您所看到的,您退出 for 循环时从未在第 13 行调用 else。此外,if not run_started也从未调用过final 。您的代码按照设计的方式工作,尽管可能不是您希望的方式。HTH

回答by ely

A way that is more efficient than fully constructing the sorted list (and should work for arbitrary iterable types, containing any data types that allow for greater-than comparisons):

一种比完全构建排序列表更有效的方法(并且应该适用于任意可迭代类型,包含允许大于比较的任何数据类型):

def len_ascending_run_from_start(seq):
    vals = enumerate(seq)
    try:
        c,x = 1, vals.next()[1]
    except StopIteration:
        raise ValueError("Sequence is empty!")
    for i, cur_x in vals:
        if cur_x < x:
            break
        c,x = c+1, cur_x
    return c

E.g.:

例如:

In [44]: len_ascending_run_from_start([datetime.date(2012,1,4), datetime.date(2012,1,3), datetime.date(2012,1,5)])
Out[44]: 1

In [45]: len_ascending_run_from_start([datetime.date(2012,1,4), datetime.date(2012,1,6), datetime.date(2012,1,5)])
Out[45]: 2

In [46]: len_ascending_run_from_start([datetime.date(2012,1,4), datetime.date(2012,1,6), datetime.date(2012,1,7)])
Out[46]: 3

In [47]: len_ascending_run_from_start((1,2,3,4))
Out[47]: 4

In [48]: len_ascending_run_from_start((1,3,2,4))
Out[48]: 2

In [49]: len_ascending_run_from_start(set([1,3,2,4]))
Out[49]: 4

It could also be fun / useful to make a class such that lenautomatically reports this statistic about the underlying sequence (and keeps a simplistic cache of the result, to avoid calculating it repeatedly).

制作一个类来len自动报告有关底层序列的统计信息(并保留结果的简单缓存,以避免重复计算)也可能很有趣/有用。

class AscendingRunFromStart(object):
    def __init__(self, seq):
        self.seq = seq

    def __repr__(self):
        return self.seq.__repr__()
    __str__ = __repr__

    def __len__(self):
        if hasattr(self, "_len"):
            return self._len
        vals = enumerate(self.seq)
        c,x = 1, vals.next()[1]
        for i, cur_x in vals:
            if cur_x < x:
                break
            c,x = c+1, cur_x
        self._len = c
        return self._len

E.g.:

例如:

In [76]: x = AscendingRunFromStart([1,3,2,4])

In [77]: x
Out[77]: [1, 3, 2, 4]

In [78]: len(x)
Out[78]: 2

A good extension would be to use a Descriptor pattern to make the seqattribute of the class read-only, or to invoke an updated lencalculation whenever setis called. (Left as exercise for the reader...)

一个好的扩展是使用描述符模式使seq类的属性只读,或者在调用时调用更新的len计算set。(留给读者练习...)

回答by Greg von Winckel

How about a one-liner to tell if every number in the list x is strictly increasing?

用一行来判断列表 x 中的每个数字是否都严格递增?

[(x[k+1]-x[k])>0 for k in range(len(x)-1)].count(True) == len(x)-1

回答by slider

Well, here's my go at it. Some have suggested sorting the list, which would be O(nlogn). I propose a simpler O(n) solution

好吧,这是我的目标。有些人建议对列表进行排序,这将是 O(nlogn)。我提出了一个更简单的 O(n) 解决方案

def isAscending(list):
    previous = list[0]
    for number in list:
        if number < previous:
            return False
        previous = number
    return True