When studying python, the sorted function is inevitable. Moreover, I often forget it, so make a note of it. This uses the sorted function for the dictionary. The point to keep in mind is that y and x after lambda can be anything else. For example, you can use lambda aaa: aaa [0]. Because y and x here are just the contents of the previous list (listA, listB, listC in the example). It seems that it's okay if you hold down even here. Take a look at the example below.
listA = [3, 6, 1, 0, 10, 8, 9]
print(sorted(listA))
#Result 1
#[0, 1, 3, 6, 8, 9, 10]
listB = ['g', 'e', 't', 'b', 'a']
print(sorted(listB))
print(sorted(listB, key=lambda y: y[0]))
#Result 2
#['a', 'b', 'e', 'g', 't']
#['a', 'b', 'e', 'g', 't']
listC = [('e', 4), ('o', 2), ('!', 5), ('v', 3), ('l', 1)]
print(sorted(listC, key=lambda x: x[1]))
#Result 3
#[('l', 1), ('o', 2), ('v', 3), ('e', 4), ('!', 5)]
** Difference between sorted and sorted: **
Well then again.
Recommended Posts