(original) (raw)
hello
i was thinking about a possible improvement for the itemgetter
the documentation page shows simple examples like sorting a dictionary by its integer values, like this:
>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1)
>>> map(getcount, inventory)
[3, 2, 5, 1]
>>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
let's suppose i have dictionary where items are lists (instead of integers), and i want to sort it by the size of each list:
>>> friends = {
... 'alex': ['bob', 'jane'],
... 'mary': ['steve', 'linda', 'foo bar'],
... 'john': ['max']
... }
>>> sorted(friends.items(), key=itemgetter(1))
[('alex', ['bob', 'jane']), ('john', ['max']), ('mary', ['steve', 'linda', 'foo bar'])]
that doesn't work since itemgetter(1) will return a list, and that's not useful for sorting.
i didn't look at the code, but i suppose itemgetter is something like this:
class itemgetter:
def __init__(self, index):
self.index = index
def __call__(self, item):
return tem[self.index]
in order for that sort (and possibly a lot of other things) to work properly, we could add
a callback method for itemgetter, like this:
class itemgetter:
def __init__(self, index, callback=None):
self.index = index
self.callback = callback
def __call__(self, item):
return self.callback and self.callback(item[self.index]) or item[self.index]
so, we could easly sort by the amount of data in each list, like this:
>>> sorted(friends.items(), key=itemgetter(1, callback=len))
[('john', ['max']), ('alex', ['bob', 'jane']), ('foo', ['bar', 'steve', 'linda'])]
what do you guys think about it? please correct me if i'm wrong.
--
Ship ahoy! Hast seen the While Whale?
- Melville's Captain Ahab