0

If I have a the list

listOfFiles = [<str>,<intA>,<intB>]

How can I sort this list first by intA then by intB?

The end result would look like

<str>,1,1
<str>,1,2
<str>,1,3
<str>,2,1
<str>,2,2
etc

3 Answers 3

9

Use a compound key (or rather, a sequence as a key).

listOfFiles.sort(key=operator.itemgetter(1, 2))
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, didn't know that you could pass multiple arguments to operator.itemgetter.
0

Python list sorting is done in place and is guaranteed to be stable after 2.4 (I believe, it may have been 2.5). That means you can sort like so and should get the results you want:

listOfFiles.sort(key = lambda x: x[2])

listOfFiles.sort(key = lambda x: x[1])

I presume you actually have a list of lists, or a list of tuples. If not, please provide a more complete example of your data structure.

1 Comment

I would just make the lambda x[1], x[2] so you only need to sort once.
0

This also works:

listOfFiles.sort(key=lambda x: (x[1], x[2]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.