在列表中查找最大出现次数

2024-06-16 09:32:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出一种方法,在列表列表中,值出现的频率最高。我试着用计数器,这给了我每次不同事件的计数。我想一个解决方案,没有使用计数器,因为我不熟悉它,但如果有人可以帮助它,我不反对。在

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_)

颜色列表:

^{pr2}$

使用计数器

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

Tags: 方法inself列表forgetifcounter
3条回答

您可以使用字典:

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}

要获取最大颜色和计数:

^{pr2}$

首先,我会将列表展开,如下所示:

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

然后使用字典理解遍历列表以创建频率字典,如下所示:

^{pr2}$

然后从字典中找出最大值,如下所示:

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

另外,嵌套if语句可能不需要存在于代码中。在第一个if语句中,你要确保新卡。稀有等于“神话罕见”,所以第二个if语句总是返回true,因为新卡。稀有在这一点上总是“不等于”或“没有”。你可以去掉第二个if语句,你的代码也能正常工作。在

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_)

要获得最常用的颜色,请使用^{}^{}方法。第一项是最常见的:

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)]

如果你想自己动手,你可以用字典:

^{pr2}$

相关问题 更多 >