如何检查列表是否已排序? [英] How do I check if a list is sorted?
问题描述
可能重复:
用Python方式检查列表是否已排序或不是
Possible Duplicate:
Pythonic way to check if a list is sorted or not
在python中,如何测试数字列表是否已排序?
In python, how do I test whether a list of numbers is already sorted or not?
推荐答案
这只能通过遍历列表(隐式或显式)来实现:
This is only possible by iterating over the list (implicitly or explicitly):
all(b >= a for a, b in zip(the_list, the_list[1:])
但是,如果需要对它进行排序,为什么不对它进行排序呢?在已经排序的列表上,Python的排序算法将非常便宜-可能比上面的测试便宜.
But why not just sort it if you need it to be sorted? Python's sorting algorithm will be really cheap on an already sorted list -- possibly cheaper than the test above.
因为这变成了关于性能的讨论,所以这里是使用惰性迭代器的版本:
Because this turned into a discussion about performance, here is a version using lazy iterators:
it = iter(the_list)
it.next()
all(b >= a for a, b in itertools.izip(the_list, it))
对于具有一百万个条目的随机排序列表,这比the_list == sorted(the_list)
快10000倍以上.
For a randomly ordered list with a million entries, this is more than 10000 times faster than the_list == sorted(the_list)
.
这篇关于如何检查列表是否已排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!