How to sort a list/tuple of lists/tuples by the element at a given index?

前端 未结 10 1665
南笙
南笙 2020-11-21 07:09

I have some data either in a list of lists or a list of tuples, like this:

data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
相关标签:
10条回答
  • 2020-11-21 07:53

    For sorting by multiple criteria, namely for instance by the second and third elements in a tuple, let

    data = [(1,2,3),(1,2,1),(1,1,4)]
    

    and so define a lambda that returns a tuple that describes priority, for instance

    sorted(data, key=lambda tup: (tup[1],tup[2]) )
    [(1, 1, 4), (1, 2, 1), (1, 2, 3)]
    
    0 讨论(0)
  • 2020-11-21 07:57

    itemgetter() is somewhat faster than lambda tup: tup[1], but the increase is relatively modest (around 10 to 25 percent).

    (IPython session)

    >>> from operator import itemgetter
    >>> from numpy.random import randint
    >>> values = randint(0, 9, 30000).reshape((10000,3))
    >>> tpls = [tuple(values[i,:]) for i in range(len(values))]
    
    >>> tpls[:5]    # display sample from list
    [(1, 0, 0), 
     (8, 5, 5), 
     (5, 4, 0), 
     (5, 7, 7), 
     (4, 2, 1)]
    
    >>> sorted(tpls[:5], key=itemgetter(1))    # example sort
    [(1, 0, 0), 
     (4, 2, 1), 
     (5, 4, 0), 
     (8, 5, 5), 
     (5, 7, 7)]
    
    >>> %timeit sorted(tpls, key=itemgetter(1))
    100 loops, best of 3: 4.89 ms per loop
    
    >>> %timeit sorted(tpls, key=lambda tup: tup[1])
    100 loops, best of 3: 6.39 ms per loop
    
    >>> %timeit sorted(tpls, key=(itemgetter(1,0)))
    100 loops, best of 3: 16.1 ms per loop
    
    >>> %timeit sorted(tpls, key=lambda tup: (tup[1], tup[0]))
    100 loops, best of 3: 17.1 ms per loop
    
    0 讨论(0)
  • 2020-11-21 07:57

    Sorting a tuple is quite simple:

    tuple(sorted(t))
    
    0 讨论(0)
  • 2020-11-21 08:01
    sorted_by_second = sorted(data, key=lambda tup: tup[1])
    

    or:

    data.sort(key=lambda tup: tup[1])  # sorts in place
    
    0 讨论(0)
提交回复
热议问题