I have the following code:
# initialize
a = []
# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John", 8, "Student"])
a.append(["Paul", 22, "Car Dealer"])
a.append(["Mark", 66, "Retired"])
# sort the table by age
import operator
a.sort(key=operator.itemgetter(1))
# print the table
print(a)
It creates a 4x3 table and then it sorts it by age. My question is, what exactly key=operator.itemgetter(1)
does? Does the operator.itemgetter
function return the item's value? Why can't I just type something like key=a[x][1]
there? Or can I? How could with operator print a certain value of the form like 3x2
which is 22
?
How does exactly Python sort the table? Can I reverse-sort it?
How can I sort it based on two columns like first age, and then if age is the same b name?
How could I do it without operator
?