Reputation: 190769
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?
Upvotes: 1
Views: 373
Reputation: 70592
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()
.
Upvotes: 3
Reputation: 9726
import random
print sorted(a, key=lambda m: (len(m), random.random()))
Upvotes: 4
Reputation: 36011
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.
Upvotes: 4