Sorting a list by nested tuple values

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.

+5
4

, key=lambda x: x[0][1]

+8

, , .

.

, , -- NumPy. - . , . , (a, b):

>>> arr = numpy.array([((2,1), 1),((1,3), 1),((3,6), 1),((4,5), 2)],
                  dtype=[('pos', [('a', int), ('b', int)]), ('count', int)])
>>> print numpy.sort(arr, order=['count', 'pos'])
[((1, 3), 1) ((2, 1), 1) ((3, 6), 1) ((4, 5), 2)]

( C).

Python, , (count, a, b) , , , Python ( ).

+2

:

l = [((2,1), 1), ((1,3), 1), ((3,6), 1), ((4,5), 2)]

def deep_get(*idx):
    def g(t):
        return reduce(lambda t, i: t[i], idx, t)
    return g

>>> sorted(l, key=deep_get(0,1))
[((2, 1), 1), ((1, 3), 1), ((4, 5), 2), ((3, 6), 1)]

:

def deep_get(*idx):
    return lambda t: reduce(lambda t, i: t[i], idx, t)

:

sorted(l, key=lambda t: reduce(lambda t, i: t[i], (0,1), t))
+1

. :

def sort_one(d):
    result = d.items()
    result.sort(key=lambda x: (-x[1], x[0]))
    return result

x[1], , .

, sort Python . (a, b) ( ). , :

def sort_two(d):
    result = d.items()
    result.sort()
    result.sort(key=itemgetter(1), reverse=True)
    return result

10-20% ( , ), 0,5 Q6600 ( ) 100 . . , , .

0

All Articles