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

前端 未结 10 1672
南笙
南笙 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: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
    

提交回复
热议问题