<分区>
Possible Duplicate:
Pythonic way to check if a list is sorted or not
在 python 中,如何测试数字列表是否已经排序?
<分区>
Possible Duplicate:
Pythonic way to check if a list is sorted or not
在 python 中,如何测试数字列表是否已经排序?
最佳答案
这只有通过遍历列表(隐式或显式)才有可能:
all(b >= a for a, b in zip(the_list, the_list[1:])
但如果需要排序,为什么不直接排序呢? Python 的排序算法在已经排序的列表上会非常便宜——可能比上面的测试便宜。
编辑:因为这变成了关于性能的讨论,这里是一个使用惰性迭代器的版本:
it = iter(the_list)
it.next()
all(b >= a for a, b in itertools.izip(the_list, it))
对于包含一百万个条目的随机排序列表,这比 the_list == sorted(the_list)
快 10000 多倍。
关于python - 如何检查列表是否已排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4710763/