如何计算列表的字典值中最频繁出现的值?

时间:2020-10-24 08:36:11

标签: python list dictionary

我有一本类似如下的字典:

{'0013E139F1F37264': ['33984', '72190', 'V8909', '4019', '73303', '4011', '49390', '4019', '', 'V5869', '4019', '79029', '920', '', '', '33829', 'V1582', 'V5889', '72885', '', '', '25000', '25000', '', '', '', '', '78079', '4241', '', '', '', '', '', '73710', '', '', '', '', '', 'V5865', '', '', '', '', '', '73390', '', '', '', '', '', 'V5861', ''], '0014FFD71C90B753': ['36650', 'V811', 'V559', '73642', 'V5866', '', '', '4019', '2449', '', '', '72252', '', '', '', '', '', '', '', '', '', '', 
'', '', '', '', '', '', '', '', '', '', '', '', '', ''], '00151A878F9A2C0D': ['4019', '38640', '73303', '7915', '36651', '73302', '8470', '78900', 'V7641', '42731', '7840', '', 'V5861', 'V431', '2724', '', '', '', '25000', '4279', '', '41400', '2724', '', '', '', '', '2720', '2859', '', '', '27802', '', '', '', '', '', '', '', '', '71690', '', '', '', '', '', '', '', '', '7291', '', '', '', '', '', '', '', '', 'V5869', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''], '00157F1570C74E09': ['3005', '36619', '30000', '53081', '', '2469', '', '', '', '', '', '', '', '', '', '', '', '']}

这不像普通的字典,因为值在列表中。我只想计算每个键中不是的最频繁的值。我不能使用counter方法或python中的任何其他库。我通常会使用counter来做到这一点,但对如何进一步前进感到困惑。

我的输出应如下所示(数字为示例):

0013E139F1F37264 : 2
00151A878F9A2C0D: 3
00157F1570C74E09 : 4

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

test = {'0013E139F1F37264': ['33984', '72190', 'V8909', '4019', '73303', '4011', '49390', '4019', '', 'V5869', '4019', '79029', '920', '', '', '33829', 'V1582', 'V5889', '72885', '', '', '25000', '25000', '', '', '', '', '78079', '4241', '', '', '', '', '', '73710', '', '', '', '', '', 'V5865', '', '', '', '', '', '73390', '', '', '', '', '', 'V5861', '']}
    
test_list = list(test['0013E139F1F37264'])

filt = list(filter(lambda x: x != '', test_list))
        
result = max(set(filt), key = test_list.count)`

结果给出4019的输出

说明:

您首先要从字典值中创建一个具有列表类型的变量,然后使用过滤器功能将空元素过滤掉。