Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

  1. How does exactly Python sort the table? Can I reverse-sort it?

  2. How can I sort it based on two columns like first age, and then if age is the same b name?

  3. How could I do it without operator?

like image 853
Nickl Avatar asked Sep 03 '13 15:09

Nickl


People also ask

How does operator Itemgetter work?

operator. itemgetter() that fetches an “item” using the operand's __getitem__() method. If multiple values are returned, the function returns them in a tuple. This function works with Python dictionaries, strings, lists, and tuples.

What is key Itemgetter Python?

itemgetter() for the key parameter. itemgetter() in the standard library operator returns a callable object that fetches a list element or dictionary value.

What is the sorted function in Python?

The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.

What is import operator in Python?

The Python operator module is one of the inbuilt modules in Python, and it provides us with a lot of functions such as add(x, y), floordiv(x, y) etc., which we can use to perform various mathematical, relational, logical and bitwise operations on two input numbers.


2 Answers

Looks like you're a little bit confused about all that stuff.

operator is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.

So, you can't use key=a[x][1] there, because python has no idea what x is. Instead, you could use a lambda function (elem is just a variable name, no magic there):

a.sort(key=lambda elem: elem[1]) 

Or just an ordinary function:

def get_second_elem(iterable):     return iterable[1]  a.sort(key=get_second_elem) 

So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.

Other questions:

  1. Yes, you can reverse sort, just add reverse=True: a.sort(key=..., reverse=True)
  2. To sort by more than one column you can use itemgetter with multiple indices: operator.itemgetter(1,2), or with lambda: lambda elem: (elem[1], elem[2]). This way, iterables are constructed on the fly for each item in list, which are than compared against each other in lexicographic(?) order (first elements compared, if equal - second elements compared, etc)
  3. You can fetch value at [3,2] using a[2,1] (indices are zero-based). Using operator... It's possible, but not as clean as just indexing.

Refer to the documentation for details:

  1. operator.itemgetter explained
  2. Sorting list by custom key in Python
like image 152
J0HN Avatar answered Sep 17 '22 12:09

J0HN


Answer for Python beginners

In simpler words:

  1. The key= parameter of sort requires a key function (to be applied to be objects to be sorted) rather than a single key value and
  2. that is just what operator.itemgetter(1) will give you: A function that grabs the first item from a list-like object.

(More precisely those are callables, not functions, but that is a difference that can often be ignored.)

like image 43
Lutz Prechelt Avatar answered Sep 21 '22 12:09

Lutz Prechelt