How do operator.itemgetter() and sort() work?

前端 未结 5 2040
孤城傲影
孤城傲影 2020-12-12 09:29

I have the following code:

# initialize
a = []

# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John&         


        
5条回答
  •  悲哀的现实
    2020-12-12 10:22

    You are asking a lot of questions that you could answer yourself by reading the documentation, so I'll give you a general advice: read it and experiment in the python shell. You'll see that itemgetter returns a callable:

    >>> func = operator.itemgetter(1)
    >>> func(a)
    ['Paul', 22, 'Car Dealer']
    >>> func(a[0])
    8
    

    To do it in a different way, you can use lambda:

    a.sort(key=lambda x: x[1])
    

    And reverse it:

    a.sort(key=operator.itemgetter(1), reverse=True)
    

    Sort by more than one column:

    a.sort(key=operator.itemgetter(1,2))
    

    See the sorting How To.

提交回复
热议问题