Search code examples
pythonalgorithmshuffle

How to sort a list of lists in Python without having repeated names together


I have the following list with names and ages:

[['John', 8], ['John', 8], ['John', 8], ['Mary', 7], ['Mary', 7], ['Mike', 9], ['Mike', 9]]

How to sort it, with Python, in a random way and without having same name next to each other. For example (sorted):

[['John', 8], ['Mary', 7], ['Mike', 9], ['John', 8], ['Mike', 9], ['Mary', 7], ['John', 8]]

My real case has about 250 names and same name does not repeats more than 50 times, that means that always there is a possible solution.


Solution

  • Thank you for all the answers and suggestions.

    Unfortunately I could not adapt any of the proposed solutions to work with my real data, and I had to develop a solution, that you can see and comment here:

    Python: sorting a matrix of data (list of lists) to have equal "names" at the biggest distance of each other