What does this mean: key=lambda x: x[1] ?

前端 未结 6 2030
离开以前
离开以前 2021-02-05 06:17

I see it used in sorting, but what do the individual components of this line of code actually mean?

key=lambda x: x[1]

What\'s lambda

6条回答
  •  忘了有多久
    2021-02-05 06:52

    One more example of usage sorted() function with key=lambda. Let's consider you have a list of tuples. In each tuple you have a brand, model and weight of the car and you want to sort this list of tuples by brand, model or weight. You can do it with lambda.

    cars = [('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000), ('bmw', 'x5', 1700)]
    
    print(sorted(cars, key=lambda car: car[0]))
    print(sorted(cars, key=lambda car: car[1]))
    print(sorted(cars, key=lambda car: car[2]))
    

    Results:

    [('bmw', 'x5', 1700), ('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000)]
    [('lincoln', 'navigator', 2000), ('bmw', 'x5', 1700), ('citroen', 'xsara', 1100)]
    [('citroen', 'xsara', 1100), ('bmw', 'x5', 1700), ('lincoln', 'navigator', 2000)]
    

提交回复
热议问题