I have a number of names divided into several lists. I am printing all the names which occur in more than one list, sorted by the number of occurrences.
What is a better/easier/more pythonic way of doing this? I feel like my solution is overly complicated.
import numpy as np
list_1 = ['John Cleese', 'Terry Gilliam']
list_2 = ['Eric Idle', 'Terry Jones', 'Michael Palin']
list_3 = ['Graham Chapman', 'Sir Lancelot the Brave', 'Terry Jones']
list_4 = ['Arthur, King of the Britons', 'Terry Jones', 'John Cleese']
list_5 = ['Michael Palin', 'Sir Robin the Not-Quite-So-Brave-as-Sir-Lancelot']
all = sorted(np.unique(list_1+list_2+list_3+list_4+list_5))
def in_how_many(name):
result = 0
if name in list_1:
result += 1
if name in list_2:
result += 1
if name in list_3:
result += 1
if name in list_4:
result += 1
if name in list_5:
result += 1
return result
names_list = []
for name in all:
if in_how_many(name) > 1:
name_dict = {'name': name, 'value': in_how_many(name)}
names_list.append(name_dict)
for person in sorted(names_list, key=lambda k: k['value'], reverse=True):
print '\'%s\' is in %s lists' % (person['name'], person['value'])
This prints:
'Terry Jones' is in 3 lists
'John Cleese' is in 2 lists
'Michael Palin' is in 2 lists