sorted , list.sort()
These two are python's built-in functions that sort the list. It's okay if it's a one-dimensional array because you don't have to think too much about it, but it's annoying when it comes to multiple orders. So, here is the explanation as a method when it is multi-order
a = [ [1,7,'z'], [3,2,'x'], [1,8,'r'], [2,2,'s'], [1,9,'b'], [2,2,'a'] ] print sorted(a, key=lambda x:x)
If you write this
key = lambda x: x , the list will be sorted by index = 2, here by characters.
However, I wasn't sure if passing this lambda function would work.
Apparently I was still stuck in a language where I couldn't rename old-fashioned functions.
def f1(data,function): p =  for i in data: p.append(function(i)) return p def f2(num): return num/2. a = f1 #Variable a meaning the function f1 b = f2 #Variable b meaning the function f2 print f1(3,f2) #With this result print a(3,b) #This result is the same
So in sorted, the key wasn't specified to compare the second element, It means that a function that returns the element to be compared was specified.
sort(a,key=str.lower) sort(a,key=lambda x:x) # for i in a: # key(i) =>Comparison factor
This means that you can even throw in your own elaborate functions.
def function_x(something): ''' Something that returns very elaborate and unexpected results ''' return result a = [ [1,7,'z'], [3,2,'x'], [1,8,'r'], [2,2,'s'], [1,9,'b'], [2,2,'a'] ] print sorted(a,key=function_x)
For example, if you create a function that returns the soccer world ranking when you throw a country name and sort it, You can sort by country name and soccer ranking. (No demand) This may be useful and unexpectedly useful.