【问题标题】:Find max occurrences in list of lists在列表列表中查找最大出现次数
【发布时间】:2018-05-08 00:41:55
【问题描述】:

我正在尝试找出在列表列表中最常出现值的方法。我尝试使用 Counter ,这给了我每次不同事件的计数。我想要一个不使用 Counter 的解决方案,因为我不熟悉它,但如果有人可以提供帮助,我不反对。

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

颜色列表列表:

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

使用计数器

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

【问题讨论】:

  • 别害羞,你会喜欢 Counter。
  • 我很想看看它是如何工作的。我的意思是它能够按颜色提取计数。只需要显示最大值
  • 我现在需要帮助解决 NoneType 不可迭代错误
  • 每当我使用 Mythic Rare 时它都有效,但在我使用 Uncommon 时无效

标签: python list class methods


【解决方案1】:

要获得最常见的颜色,请使用Countermost_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)]

如果你想自己做,你可以使用字典:

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)

【讨论】:

  • 我使用了这种方法,当我运行它时,它是 NoneType 不可迭代的?有什么想法吗?
【解决方案2】:

您可以使用字典:

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}

要获得最大颜色和数量:

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

【讨论】:

    【解决方案3】:

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

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

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

    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}
    

    然后从字典中取出最大值,像这样:

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

    此外,嵌套的 if 语句可能不需要存在于您的代码中。在第一个 if 语句中,您确保 newCard.rarity 等于“Mythic Rare”,因此第二个 if 语句将始终返回 true,因为此时 newCard.rarity 将始终“不等于”与“None” .你可以去掉第二个 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_)
    

    【讨论】:

    • 不是用第二个if语句的意思,应该是if newCard.get_colors!="None"
    【解决方案4】:

    您也可以只使用defaultdict 来收集计数:

    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
    

    产量:

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

    然后通过简单的itemgetter 获得最大值:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-19
      • 2021-11-28
      • 2021-06-11
      • 2015-10-08
      • 1970-01-01
      • 2021-04-02
      • 2011-10-22
      • 2021-12-27
      相关资源
      最近更新 更多