Edgewall Software

Changes between Version 3 and Version 4 of HelperFunctions


Ignore:
Timestamp:
Aug 18, 2006, 12:11:32 PM (18 years ago)
Author:
Arnar Birgisson
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • HelperFunctions

    v3 v4  
    142142}}}
    143143
     144=== Similar version with a dict, counts any hashable types ===
     145
     146The previous function can only count occurrences of numbers.
     147This counts occurrences of any hashable types and returns a dict instead of a list.
     148{{{
     149#!python
     150def countitemoccurrences(items, requireditems=[]):
     151    """Takes a list of hashable items and returns a dict whose keys are those
     152    items and the values are the counts of how many times each item appers in the list.
     153   
     154    If the list requireditems is specified it's values are guaranteed to be keys
     155    in the resulting dict, even if they don't appear in items in which case the count will be 0
     156   
     157    Examples:
     158    >>> counttypes('blue green green'.split(), 'blue red green'.split())
     159    {'blue': 1, 'green': 2, 'red': 0}
     160    """
     161    counts = dict()
     162    for i in requireditems:
     163        counts[i] = 0
     164    for i in items:
     165        counts[i] = counts.get(i, 0) + 1
     166    return counts
     167}}}
     168
    144169----
    145170See also: MarkupGuide, MarkupRecipes