Ignore:
Timestamp:
23 Mar 2012, 03:02:21 (13 years ago)
Author:
uli
Message:

Add helper function to sort lists with preferred values first.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • main/waeup.kofa/trunk/src/waeup/kofa/utils/helpers.py

    r7943 r7968  
    508508        result.append(name)
    509509    return result
     510
     511def get_sorted_preferred(tuples_iterable, preferred_list):
     512    """Get a list of tuples (<TITLE>,<TOKEN>) with values in
     513    `preferred_list` put in front.
     514
     515    The rest of the tuples iterable is returned in orginal order. This
     516    is useful for putting default entries on top of (already sorted)
     517    lists of choice values, for instance when sorting countries and
     518    their code.
     519
     520    Sample:
     521
     522    We have a list of tuples with uppercase 'titles' and lowercase
     523    'tokens'. This list is already sorted but we want certain values
     524    of this list to show up before other values. For instance we want
     525    to see the 'C' entry to come first.
     526
     527      >>> get_sorted_preferred([('A','a'), ('B','b'), ('C','c')],
     528      ...                       ['c'])
     529      (('C', 'c'), ('A', 'a'), ('B', 'b'))
     530
     531    i.e. the entry with 'c' as second value moved to head of result.
     532
     533    We can also require multiple entries at head of list:
     534
     535      >>> get_sorted_preferred([('A','a'), ('B','b'), ('C','c')],
     536      ...                       ['b', 'c'])
     537      (('B', 'b'), ('C', 'c'), ('A', 'a'))
     538
     539    We required the 'b' entry to come before the 'c' entry and then
     540    the rest of the input list. That's what we got.
     541
     542    The result is returned as a tuple of tuples to keep order of values.
     543    """
     544    result = [None for x in preferred_list]
     545    for title, code in tuples_iterable:
     546        if code in preferred_list:
     547            index = preferred_list.index(code)
     548            result[index] = (title, code)
     549        else:
     550            result.append((title, code))
     551    return tuple(result)
Note: See TracChangeset for help on using the changeset viewer.