简体   繁体   中英

Find max occurrences in list of lists

I'm trying to find out a way to which value occurs the most often in a list of lists. I tried using Counter and that gives me the counts for each different occurrence. I would like a solution that was not using Counter since I am unfamiliar with it but if someone can help with it I'm not opposed.

def get_uncommon_colors(self):
    uncommon_colors_list=[]
    colors=['black','red','white','blue']
    for newCard in self.cardlist:
        newCard.rarity.split()
        if newCard.rarity=="Mythic Rare":
            if newCard.get_colors!="None":
                uncommon_colors_list.append(newCard.get_colors())
        else:
            continue
        #test=(Counter(x for sublist in uncommon_colors_list for x in sublist))
    return(uncommon_)

List of lists of colors:

[['White'],
 ['Blue'],
 ['Blue'],
 ['Black'],
 ['Red'],
 ['Red'],
 ['Green'],
 ['Green'],
 ['Red', 'Green'],
 ['White', 'Green'],
 ['Black', 'Red'],
 ['White', 'Blue'],
 ['Blue', 'Black'],
 ['White', 'Blue'],
 ['Blue', 'Red', 'Green']]

Using Counter

Counter({'Black': 3, 'Blue': 6, 'Green': 5, 'Red': 5, 'White': 4})

To get the most frequent colour use the most_common() method of the Counter . The first item is the most common:

from collections import Counter

list_of_lists = [['White'], ['Blue'], ['Blue'], ['Black'], ['Red'], ['Red'], ['Green'], ['Green'], ['Red', 'Green'], ['White', 'Green'], ['Black', 'Red'], ['White', 'Blue'], ['Blue', 'Black'], ['White', 'Blue'], ['Blue', 'Red', 'Green']]

>>> Counter(colour for sublist in list_of_lists for colour in sublist).most_common(1)
[('Blue', 6)]

If you wanted to do this yourself you could use a dictionary:

d = {}

for sublist in list_of_lists:
    for colour in sublist:
        d[colour] = d.get(colour, 0) + 1

>>> max(d.items(), key=lambda t: t[1])
('Blue', 6)

You can use dictionaries:

l = [['White'],
 ['Blue'],
 ['Blue'],
 ['Black'],
 ['Red'],
 ['Red'],
 ['Green'],
 ['Green'],
 ['Red', 'Green'],
 ['White', 'Green'],
 ['Black', 'Red'],
 ['White', 'Blue'],
 ['Blue', 'Black'],
 ['White', 'Blue'],
 ['Blue', 'Red', 'Green']]

d = {}
for i in l:
    for j in i:
        if d.get(j):
            d[j] += 1
        else:
            d[j] = 1           

print(d)
{'Black': 3, 'Green': 5, 'Red': 5, 'Blue': 6, 'White': 4}

To get max color and count:

print(max(d, key=d.get),d[max(d, key=d.get)])
Blue 6

You could also just use a defaultdict to collect the counts:

from collections import defaultdict
from operator import itemgetter

def count_occurences(lst):

    # flatten the list, many ways to do this
    all_colors = [color for sublist in lst for color in sublist]

    freq = defaultdict(int)

    for color in all_colors:
        freq[color] += 1

    return freq

Which yields:

>>> occurences = count_occurences(nested_colours)
>>> print(occurences)
defaultdict(<class 'int'>, {'Black': 3, 'Blue': 6, 'White': 4, 'Red': 5, 'Green': 5})

Then get the max with simply itemgetter :

>>> print(max(occurences.items(), key = itemgetter(1)))
('Blue', 6)

I would first flatten the list of lists, like this:

flattened_color_list = [item for sub_list in color_list for item in sub_list]

Then iterate through the list using a dictionary comprehension to create your frequency dictionary, like this:

frequency = {}
{item: 1 if item not in frequency and not frequency.update({item: 1}) else frequency[item] + 1 if not frequency.update({item: frequency[item] + 1}) else 1 for item in flattened_color_list}

Then get the largest value out of the dictionary, like this:

max(frequency.iterkeys(), key=(lambda key: frequency[key]))

Also, the nested if statement probably doesn't need to exist in your code. In the first if statement, you're ensuring that newCard.rarity is equal to "Mythic Rare," so the second if statement would always return true, since newCard.rarity would always be "not equal" to "None" at that point. You could get rid of the second if statement and your code would work the same.

def get_uncommon_colors(self):
    uncommon_colors_list=[]
    colors=['black','red','white','blue']
    for newCard in self.cardlist:
        newCard.rarity.split()
        if newCard.rarity=="Mythic Rare":
            if newCard.rarity!="None":
                uncommon_colors_list.append(newCard.get_colors())
        else:
            continue
        #test=(Counter(x for sublist in uncommon_colors_list for x in sublist))
    return(uncommon_)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM