I have the following list created from a sorted csv
list1 = sorted(csv1, key=operator.itemgetter(1))
I would actually like to sort the list by two criteria: first by the value in field 1 and then by the value in field 2. How do I do this?
本文介绍如何使用Python对列表进行基于两个排序标准的排序操作,包括直接使用itemgetter方法和通过稳定排序特性分步实现的方法。
|
59
20
| |
|
add a comment
|
|
66
|
like this:
| |||
|
100
|
Replying to this dead thread for archive. No need to import anything when using lambda functions.
| ||||||||||||||||||||
|
|
8
|
Python has a stable sort, so provided that performance isn't an issue the simplest way is to sort it by field 2 and then sort it again by field 1. That will give you the result you want, the only catch is that if it is a big list (or you want to sort it often) calling sort twice might be an unacceptable overhead.
Doing it this way also makes it easy to handle the situation where you want some of the columns reverse sorted, just include the 'reverse=True' parameter when necessary. Otherwise you can pass multiple parameters to itemgetter or manually build a tuple. That is probably going to be faster, but has the problem that it doesn't generalise well if some of the columns want to be reverse sorted (numeric columns can still be reversed by negating them but that stops the sort being stable). So if you don't need any columns reverse sorted, go for multiple arguments to itemgetter, if you might, and the columns aren't numeric or you want to keep the sort stable go for multiple consecutive sorts. Edit: For the commenters who have problems understanding how this answers the original question, here is an example that shows exactly how the stable nature of the sorting ensures we can do separate sorts on each key and end up with data sorted on multiple criteria:
This is a runnable example, but to save people running it the output is:
Note in particular how in the second step the | ||||||||||||||||||||
|
|
3
|
| ||||||||
|
498
operatoris a module that needs to be imported. – trapicki Aug 28 '13 at 14:45