Coverage for mtools.util.grouping : 48%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
for item in iterable: self.add(item, group_by)
""" General purpose class to group items by certain criteria. """
# if group_by is a function, use it with item as argument
# if the item has attribute of group_by as string, use that as key elif isinstance(group_by, str) and hasattr(item, group_by): key = getattr(item, group_by)
else: key = None # try to match str(item) with regular expression if isinstance(group_by, str): match = re.search(group_by, str(item)) if match: if len(match.groups()) > 0: key = match.group(1) else: key = match.group()
return len(self.groups)
return self.groups.keys()
return self.groups.values()
return self.groups.items()
group_by = self.group_by
for g in groups: for item in groups[g]: self.add(item, group_by)
""" will take all elements from the from_group and add it to the to_group. """ if from_group not in self.keys() or len(self.groups[from_group]) == 0: return
if from_group in self.groups: del self.groups[from_group]
""" sorts the groups by the number of elements they contain, descending. Also has option to limit the number of groups. If this option is chosen, the remaining elements are placed into another group with the name specified with others_label. if discard_others is True, the others group is removed instead. """
# sort groups by number of elements
# if group-limit is provided, combine remaining groups
# now group together all groups that did not make the limit if not discard_others: group_keys = self.groups.keys()[ group_limit-1: ] self.groups.setdefault(others_label, list()) else: group_keys = self.groups.keys()[ group_limit: ]
# only go to second last (-1), since the 'others' group is now last for g in group_keys: self.groups[others_label].extend(self.groups[g]) del self.groups[g]
# remove if empty if others_label in self.groups and len(self.groups[others_label]) == 0: del self.groups[others_label]
# remove others group regardless of limit if requested del self.groups[others_label]
# Example items = [1, 4, 3, 5, 7, 8, 6, 7, 9, 8, 6, 4, 2, 3, 3, 0]
grouping = Grouping(items, r'[3, 4, 5, 6, 7]') grouping.sort_by_size(group_limit=1, discard_others=True) # grouping.move_items('no match', 'foo')
grouping.regroup(lambda x: 'even' if x % 2 == 0 else 'odd')
for g in grouping: print g, grouping[g]
|