对于list
说l = [1, 2, 3, 4]
如何以Python方式比较l[0] < l[1] < l[2] < l[3]
?
那这个呢:
l == sorted(l)
There's a general approach, that consists in zipping the list with itself, with an offset.
In this situation, you can wrap it up in a list comprehension:
[a < b for a, b in zip(l[:-1], l[1:])]
# [l[0] < l[1], l[1] < l[2], ...]
This will give you a list of booleans. To check if the list is globally sorted, you can use all
:
all([a < b for a, b in zip(l[:-1], l[1:])])
But then, you don't need to build the actual list, a generator is enough:
all(a < b for a, b in zip(l[:-1], l[1:]))
Notice that the square brackets []
are dropped: the elements of the comprehensions will be evaluated lazily, which will avoid the creation of a useless list.
This solution has a O(n)
complexity: you iterate twice over l
with the zip
, then once over the zipped values with all
.
On the other hand, l == sorted(l)
looks smart and is elegant, but you'll have to pay the O(n*log(n))
cost of sorting l
. If your goal is to sort l
if it is not sorted, just directly call l.sort()
.
尝试这个:
comparisons = [l[i] < l[i+1] for i in range(len(l) - 1)]
你可以这样
all(l[x]<l[x+1] for x in range(len(l)-1))
另一种方法是使用.sort()方法,在这种情况下,您必须完全返回一个新列表。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.