Determine if a list is in descending order

前端 未结 7 2497
孤城傲影
孤城傲影 2020-12-03 17:35

I am trying to write a function that will test whether or not a list is in decending order. This is what I have so far, but it doesn\'t seem to be working for all lists. <

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 18:39

    You can do this easily with a generator expression and the all() builtin:

    all(earlier >= later for earlier, later in zip(seq, seq[1:]))
    

    For example:

    >>> seq = [9, 8, 5, 1, 4, 3, 2] 
    >>> all(earlier >= later for earlier, later in zip(seq, seq[1:]))
    False
    >>> seq = [9, 8, 5, 4, 3, 2] 
    >>> all(earlier >= later for earlier, later in zip(seq, seq[1:]))
    True
    

    This should be nice and fast as it avoids python-side loops, short circuits nicely (if you use itertools.izip() in 2.x), and is nice and clear and readable (avoiding looping over indices, for example).

    Note that a generic solution for all iterators (not just sequences) is possible too:

    first, second = itertools.tee(iterable)
    next(second)
    all(earlier >= later for earlier, later in zip(first, second))
    

提交回复
热议问题