Namedtuples problem

Peter Otten __peter__ at web.de
Thu Feb 23 05:57:05 EST 2017


Peter Otten wrote:

> Functions to the rescue:

On second thought this was still more code than necessary.
Why not calculate a column on demand? Here's a self-containe example:

$ cat swanson_grouped_columns_virtual.py
import operator
from collections import defaultdict, namedtuple

def split_into_groups(records, key, GroupClass=list):
    groups = defaultdict(GroupClass)
    for record in records:
        groups[key(record)].append(record)
    return groups

class Group(list):
    def __getattr__(self, name):
        return [getattr(item, name) for item in self]

Record = namedtuple("Record", "title location")

records = [
    Record("foo", "here"),
    Record("foo", "there"),
    Record("bar", "everywhere"),
]

groups = split_into_groups(
    records,
    operator.attrgetter("title"),
    Group
)

print(groups["foo"].location)
$ python3 swanson_grouped_columns_virtual.py
['here', 'there']






More information about the Python-list mailing list