2014-06-13 27 views
0

我有与大多数出现在列表

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有更多次数的数量,以便IW蚂蚁更新只有3输入列表,以便在索引0处计算元件变成[3]

如果每个元件具有像1: ['9', '4', '1', '2']相等的权重将不会有变化

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

我尝试使用collection.counter但DONOT知道如何更新原有的字典,最大反复

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] 
+1

我不明白你的意思。你想通过重复次数找到键值对吗?所以'0'在这里最大?为什么'3'不是候选人?它在列表中有两个“5”值。 –

+1

您是否要求查找[mode](http://en.wikipedia.org/wiki/Mode_(statistics))?这与“最大”不同。 – chrisaycock

+0

@MartijnPieters在索引0. 3重复了很多次,所以我想更新索引0元素为3作为值。抱歉abt我的英语 –

回答

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']} 
+0

['4','4','5','5','1']这是什么。 –

+0

请检查编辑 –

+0

现在检查答案。 – furas

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