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:
- Yes, you can reverse sort, just add
reverse=True
: a.sort(key=..., reverse=True)
- 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)
- 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:
operator.itemgetter
explained
- Sorting list by custom key in Python
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…