[Python] python只在需要的时候应用装饰排序 →→→→→进入此内容的聊天室

来自 , 2019-11-25, 写在 Python, 查看 112 次.
URL http://www.code666.cn/view/3488330b
  1.     def lazyDSU_sort(seq, keys, warn=False):
  2.         """Return sorted seq, breaking ties by applying keys only when needed.
  3.  
  4.        If ``warn`` is True then an error will be raised if there were no
  5.        keys remaining to break ties.
  6.  
  7.        Examples
  8.        ========
  9.  
  10.        Here, sequences are sorted by length, then sum:
  11.  
  12.        >>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], [
  13.        ...    lambda x: len(x),
  14.        ...    lambda x: sum(x)]]
  15.        ...
  16.        >>> lazyDSU_sort(seq, keys)
  17.        [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
  18.  
  19.        If ``warn`` is True, an error will be raised if there were not
  20.        enough keys to break ties:
  21.  
  22.        >>> lazyDSU_sort(seq, keys, warn=True)
  23.        Traceback (most recent call last):
  24.        ...
  25.        ValueError: not enough keys to break ties
  26.  
  27.  
  28.        Notes
  29.        =====
  30.  
  31.        The decorated sort is one of the fastest ways to sort a sequence for
  32.        which special item comparison is desired: the sequence is decorated,
  33.        sorted on the basis of the decoration (e.g. making all letters lower
  34.        case) and then undecorated. If one wants to break ties for items that
  35.        have the same decorated value, a second key can be used. But if the
  36.        second key is expensive to compute then it is inefficient to decorate
  37.        all items with both keys: only those items having identical first key
  38.        values need to be decorated. This function applies keys successively
  39.        only when needed to break ties.
  40.        """
  41.         from collections import defaultdict
  42.         d = defaultdict(list)
  43.         keys = list(keys)
  44.         f = keys.pop(0)
  45.         for a in seq:
  46.             d[f(a)].append(a)
  47.         seq = []
  48.         for k in sorted(d.keys()):
  49.             if len(d[k]) > 1:
  50.                 if keys:
  51.                     d[k] = lazyDSU_sort(d[k], keys, warn)
  52.                 elif warn:
  53.                   raise ValueError('not enough keys to break ties')
  54.                 seq.extend(d[k])
  55.             else:
  56.                 seq.append(d[k][0])
  57.         return seq
  58.  
  59.  
  60. #//python/5047

回复 "python只在需要的时候应用装饰排序"

这儿你可以回复上面这条便签

captcha