Is there a better way to sort the list by nested values of a tuple than by writing an alternative to itemgetter that retrieves the value of a nested tuple:
def deep_get(*idx):
def g(t):
for i in idx: t = t[i]
return t
return g
>>> l = [((2,1), 1),((1,3), 1),((3,6), 1),((4,5), 2)]
>>> sorted(l, key=deep_get(0,0))
[((1, 3), 1), ((2, 1), 1), ((3, 6), 1), ((4, 5), 2)]
>>> sorted(l, key=deep_get(0,1))
[((2, 1), 1), ((1, 3), 1), ((4, 5), 2), ((3, 6), 1)]
I was thinking about using compose, but not in the standard library:
sorted(l, key=compose(itemgetter(1), itemgetter(0))
Is there something I missed in libs that will make this code more enjoyable?
Implementation should work reasonably with 100 thousand elements.
Context: I would like to sort the dictionary of elements that are a histogram. The keys are tuples (a, b), and the value is a counter. At the end, items should be sorted in descending order, a and b. An alternative is to smooth the tuple and use the itemgetter element directly, but in this way a lot of tuples will be created.