2014-06-13 47 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])