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

前端 未结 5 2043
孤城傲影
孤城傲影 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:14

    a = []
    a.append(["Nick", 30, "Doctor"])
    a.append(["John",  8, "Student"])
    a.append(["Paul",  8,"Car Dealer"])
    a.append(["Mark", 66, "Retired"])
    print a
    
    [['Nick', 30, 'Doctor'], ['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Mark', 66, 'Retired']]
    
    def _cmp(a,b):     
    
        if a[1]b[1]:
            return 1
        else:
            return 0
    
    sorted(a,cmp=_cmp)
    
    [['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]
    
    def _key(list_ele):
    
        return list_ele[1]
    
    sorted(a,key=_key)
    
    [['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]
    >>> 
    

提交回复
热议问题