这是一个快速而肮脏的解决方案,一点也不优雅,并且使用 numpy.
import numpy as np
def print_common( usrinput ):
'''prints the most common entry of usrinput, printing all entries if there is a tie '''
usrinput = np.array( usrinput )
# np.unique returns the unique elements of usrinput
unique_inputs = np.unique( usrinput )
# an array to store the counts of each input
counts = np.array( [] )
# loop over the unique inputs and store the count for each item
for u in unique_inputs:
ind = np.where( usrinput == u )
counts = np.append( counts, len( usrinput[ ind ] ) )
# find the maximum counts and indices in the original input array
max_counts = np.max( counts )
max_ind = np.where( counts == max_counts )
# if there's a tie for most common, print all of the ties
if len( max_ind[0] ) > 1:
for i in max_ind[0]:
print unique_inputs[i], counts[i]
#otherwise just print the maximum
else:
print unique_inputs[max_ind][0], counts[max_ind][0]
return 1
# two test arrays which show desired results
usrinput = ['Jim','Jim','Jim', 'Jimmy','Jimmy','Matt','Matt','Matt']
print_common( usrinput )
usrinput = ['Jim','Jim','Jim', 'Jimmy','Jimmy','Matt','Matt']
print_common( usrinput )