计算列表中出现次数最多的元素

时间:2014-06-13 12:38:35

标签: python dictionary

我有

dict = {
    0: ['9', '3', '3', '5', '1'],
    1: ['9', '4', '1', '2'],
    2: ['3', '4', '1', '5', '5'],
    3: ['4', '4', '5', '5', '1'],
    4: ['2', '8', '9', '5', '1']
}

举一个例子0:['9', '3', '3', '5', '1']这里3有更多的出现,所以我只想更新输入列表只有3,所以在索引0变为[3]

如果每个元素都具有与1: ['9', '4', '1', '2']相同的权重,则不会有任何变化

另一个['4', '4', '5', '5', '1']返回['4','5']

我尝试使用collection.counter,但不知道如何使用max repeated

更新原始字典
for i,j in dictonary.items():
    dictonary[i]=Counter(j)

预期产出:

{0: ['3'], 1: ['9', '4', '1', '2'], 2: ['5'], 3: ['4'], 4: ['2', '8', '9', '5', '1']}

修改:列表大小可能会有所不同

[1,1,1,1,1,2,2,2,2,2,3,3,3]->[1,2]
[3,3,3,3,4,4,4,4,4,5,6,6,6,6,6]->[4,6]

2 个答案:

答案 0 :(得分:0)

from collections import *

d ={0: ['9', '3', '3', '5', '1'], 1: ['9', '4', '1', '2'], 2: ['3', '4', '1', '5', '5'], 3: ['4', '5', '0', '4', '3'], 4: ['2', '8', '9', '5', '1']}

for i,j in d.items():
    c  = Counter(j)
    top = c.most_common(1)
    if top[0][1] > 1:
        d[i] = [ top[0][0] ]

print d

{0: ['3'], 1: ['9', '4', '1', '2'], 2: ['5'], 3: ['4'], 4: ['2', '8', '9', '5', '1']}

修改

from collections import *

d = {
 0: ['4', '4', '5', '5', '1'], 
 1: ['9', '4', '1', '2'], 
 2: ['3', '4', '1', '5', '5'] 
}

for i,j in d.items():

    c  = Counter(j)

    result = []

    for x in c:
        if c[x] > 1:
            result.append(x)

    if result:       
        d[i] = result

print d

{0: ['5', '4'], 1: ['9', '4', '1', '2'], 2: ['5']}

编辑:

from collections import *

d = {
 0: ['4', '4', '5', '5', '1'], 
 1: [1,1,1,1,1,2,2,2,2,2,3,3,4], 
 2: ['3', '4', '1', '5', '5']
}

for i,j in d.items():

    c  = Counter(j)

    longest = c.most_common(1)[0][1]

    if longest > 1:

        result = []

        for x in c:

            if c[x] == longest:
                result.append(x)

        d[i] = result

print d

{0: ['5', '4'], 1: [1, 2], 2: ['5']}

答案 1 :(得分:0)

您似乎正在寻找字典中每个元素的模式。

from collections import Counter

def mode(L):
  result = []
  for x in L:
    if Counter(L)[x] == max(Counter(L).values()):
      if x not in result: result.append(x)
  return result

for item in dict:
  dict[item] = mode(dict[item])