1

With this code, I get sorted list based on the length of element.

>>> a = [[1,2,3],[3,4,5,6],[7,8],[9,10,11]]
>>> print sorted(a, key=lambda m: len(m))
[[7, 8], [1, 2, 3], [9, 10, 11], [3, 4, 5, 6]]

When sorting the list of list, I need to introduce some randomness when the length of the element is the same. For the previous example. I need to get sorted results

[[7, 8], [1, 2, 3], [9, 10, 11], [3, 4, 5, 6]]

or

[[7, 8], [9, 10, 11], [1, 2, 3], [3, 4, 5, 6]]

in random.

How can I make that in Python?

2
  • Do you want it to be consistent? Or do you want it to potentially change each time you run the sort? Commented Apr 9, 2014 at 2:12
  • So do you want each list within the list to be randomized? Or just the entire contents of the main list? 1: [[8, 7], [4, 3, 6, 5], [11, 9, 10], [1, 2, 3]] 2: [[7, 8], [3, 4, 5, 6], [9, 10, 11], [1, 2, 3]] Commented Apr 9, 2014 at 2:12

3 Answers 3

4

Python's sort functions are stable, meaning that for elements that compare equal the order is unchanged from the original list. Therefore, you can shuffle the list and then sort according to the length.

import random

a = [[1,2,3],[3,4,5,6],[7,8],[9,10,11]]
random.shuffle(a)
a.sort(key = len)

Note that this code shuffles and sorts the list a in-place.

Sign up to request clarification or add additional context in comments.

Comments

4
import random    
print sorted(a, key=lambda m: (len(m), random.random()))

Comments

3

Here's an "obvious" way. In your example, it will produce the two possible outcomes with equal probability:

from random import random
a = [[1,2,3],[3,4,5,6],[7,8],[9,10,11]]
print(sorted(a, key=lambda m: (len(m), random())))

Because of the way tuple comparison works, when elements tie on the length the comparison goes on to compare the results from calling random().

2 Comments

I wasn't sure at first that this would work but I checked the documentation and indeed the key function is only evaluated once for each item in the list.
@GeoffReedy, yes, and it's good to point that out! Thank you.

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.