简体   繁体   English

如何编写代码来确定列表是否在Python中排序?

[英]How can I make a code that determines if a list is sorted or not in Python?

How would I write a function that takes a list as an argument and verifies whether or not the list is sorted? 如何编写一个将列表作为参数并验证列表是否已排序的函数?

I want it to return true if sorted and false otherwise. 我希望它在排序后返回true,否则返回false。 For example: 例如:

>>> is_sorted([1, 5, 8, 10]) 
True

>>> is_sorted([4, 1, 7, 8])
False

However, I'm unsure of how to do this with any kind of list at all 但是,我不确定如何使用任何类型的列表来执行此操作

The simplest version that gets O(n) performance: 获得O(n)性能的最简单版本:

def is_sorted(lst):
    return all(a <= b for a,b in zip(lst, lst[1:]))

An obvious way is to sort it and compare for equality with the original list: 一种明显的方法是对它进行排序,并与原始列表进行相等性比较:

#!/usr/bin/env python

def is_sorted(mylist):
    testlist = sorted(mylist[:])
    return testlist == mylist

print is_sorted([1, 4, 6, 7])
print is_sorted([1, 7, 6, 5])

outputs: 输出:

paul@horus:~/src/sandbox$ ./sorted.py
True
False
paul@horus:~/src/sandbox$ 

If you want something slightly more efficient (presuming you want to check if it's sorted in ascending order): 如果您想要更有效的方法(假设您想检查它是否按升序排序):

def is_sorted(mylist):
    last_item = mylist[0]

    for item in mylist:
        if item < last_item:
            return False
        last_item = item

    return True

This should be a O(n) solution by iterating through the list to check for values out of order. 通过遍历列表检查值是否乱序,这应该是一个O(n)解决方案。 O(n) is worst case since it returns false the first element it finds out of order. O(n)是最坏的情况,因为它发现第一个乱序的元素返回false。

#!/usr/bin/env python

def is_sorted(mylist):
    for i, val in enumerate(mylist):
        if (i > 0 and mylist[i] < mylist[i-1]):
            return False
    return True

print is_sorted([1, 4, 6, 7])
print is_sorted([1, 7, 6, 5])

Output: 输出:

True
False
def is_sorted(mylist):
    return False not in [sorted(mylist)[idx] == val for idx, val in enumerate(mylist)]

>>> is_sorted([1, 2, 3, 4])
True

>>> is_sorted([1, 2, 4, 3])
False

Here is the most simplest way to do this: 这是最简单的方法:

def is_sorted(l):
    return True if l == sorted(l) else False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM