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

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

    In order to sort a list of tuples (, ), for count in descending order and word in alphabetical order:

    data = [
    ('betty', 1),
    ('bought', 1),
    ('a', 1),
    ('bit', 1),
    ('of', 1),
    ('butter', 2),
    ('but', 1),
    ('the', 1),
    ('was', 1),
    ('bitter', 1)]
    

    I use this method:

    sorted(data, key=lambda tup:(-tup[1], tup[0]))
    

    and it gives me the result:

    [('butter', 2),
    ('a', 1),
    ('betty', 1),
    ('bit', 1),
    ('bitter', 1),
    ('bought', 1),
    ('but', 1),
    ('of', 1),
    ('the', 1),
    ('was', 1)]
    

提交回复
热议问题