Skip to content
Advertisement

Python: Get randomised mode from list of lists

list = [1, 2, 1, 2, 4]
matrix = [[3], [2], [3], [2], [9]]

When I use this function to calculate the randomised mode from a normal list it works fine.

def get_mode(numbers):
modes = statistics.multimode(numbers)
return random.choice(modes)

However I need to get the randomised mode from a list of lists and this function below only returns the last number in matrix even though it is not the mode. How would i solve this issue?

Note: I am only allowed one parameter in the function which is the list of lists

def get_mode(numbers):
for item in numbers:
    modes = statistics.multimode(item)
return random.choice(modes)

Advertisement

Answer

I guess you want to flatten your list of lists to a single list and then compute the modes. This should work then.

def get_mode(numbers):
    #Flatten list
    flatnumbers = [item for sublist in numbers for item in sublist]
    #Compute modes
    modes = statistics.multimode(flatnumbers)
    return random.choice(modes)
Advertisement