I want to rank multiple lists according to their elements how often they appear in each list. Example:
list1 = 1,2,3,4
list2 = 4,5,6,7
list3 = 4,1,8,9
result = 4,1,2,3,4,5,6,7,8 (4 is counted three times, 1 two times and the rest once)
I've tried the following but i need something more intelligent and something i can do with any ammount of lists.
l = []
l.append([ 1, 2, 3, 4, 5])
l.append([ 1, 9, 3, 4, 5])
l.append([ 1, 10, 8, 4, 5])
l.append([ 1, 12, 13, 7, 5])
l.append([ 1, 14, 13, 13, 6])
x1 = set(l[0]) & set(l[1]) & set(l[2]) & set(l[3])
x2 = set(l[0]) & set(l[1]) & set(l[2]) & set(l[4])
x3 = set(l[0]) & set(l[1]) & set(l[3]) & set(l[4])
x4 = set(l[0]) & set(l[2]) & set(l[3]) & set(l[4])
x5 = set(l[1]) & set(l[2]) & set(l[3]) & set(l[4])
set1 = set(x1) | set(x2) | set(x3) | set(x4) | set(x5)
a1 = list(set(l[0]) & set(l[1]) & set(l[2]) & set(l[3]) & set(l[4]))
a2 = getDifference(list(set1),a1)
print a1
print a2
Now here is the problem... i can do it again and again with a3,a4 and a5 but its too complex then, i need a function for this... But i don't know how... my math got stuck ;)
SOLVED: thanks alot for the discussion. As a newbee i like this system somehow: fast+informative. You helped me all out! Ty
Combining a couple of ideas already posted:
Notes:
Counter
instead ofdefaultdict(int)
.Try this one:
Usage example:
You can use any number of lists as input
Try this code:
Note: Your lists should be hashable type
Now let's generalize it (to take any iterable, loosen hashable requirement), allow key and reverse parameters (to match sorted), and rename to freq_sorted:
Example:
You can count the number of appearances of each element (a histogram), then sort by it: