Using namedtuples field names for column indices in a list of lists
Deborah Swanson
python at deborahswanson.net
Mon Jan 9 05:57:48 EST 2017
Antoon Pardon wrote, on January 09, 2017 2:35 AM
> If I understand correctly you want something like:
>
> records.sort(key = lamda rec: rec.xx)
>
> AKA
>
> from operator import attrgetter
> records.sort(key = attrgetter('xx'))
>
> or maybe:
>
> records.sort(key = lambda rec: (rec.xx,) + tuple(rec))
>
> --
> Antoon Pardon
I think you are replying to my question about sorting a namedtuple, in
this case it's called 'records'.
I think your suggestion works for lists and tuples, and probably
dictionaries. But namedtuples doesn't have a sort function.
>>> from collections import namedtuple
>>> dir(namedtuple)
['__annotations__', '__call__', '__class__', '__closure__', '__code__',
'__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__get__', '__getattribute__',
'__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__',
'__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__',
'__qualname__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__']
so nothing with records.sort will work. :(
Deborah
More information about the Python-list
mailing list