2011-04-28 52 views
3
def get_top_k(frequency, k): 
    temp = frequency 
    key = "" 
    tvalues = [] 
    values = [] 
    kk = int(k) 
    i = 0 
    for i in temp.keys(): 
     key = i 
     num = [int(frequency[key])] 
     tvalues += num 
    tvalues = bubble_sort(tvalues) 
    i = 0 
    for i in kk: 
     num = [int(tvalues[i])] 
     values += num 
    print(values) 
    i = 0 
    result = {} 
    for i in kk: 
     result += {(str(temp[values[i]])):(int(values[i]))} 
    return result 

回答

1

因爲kk = int(k)

kk只有一個單一的數字,而不是數字

數組什麼是你想怎麼辦,讓我們幫你修復它?

2

您有for i in kkkk只是一個整數。你不能遍歷一個整數,你只能遍歷一個序列/可迭代的。

如果要從0到(kk-1)進行迭代,則可能需要for i in range(kk)

+0

'xrange'也不會傷害。 ;) – aviraldg 2011-04-28 17:55:25

+0

@Aviral如果它不是Python 3.x :) – 2011-04-28 17:59:08

6

也許你的意思是

for i in range(kk): 
+1

進一步解釋:如果您確實需要遍歷一系列數字,內置函數range()就派上用場了。它生成包含算術運算的列表,例如: >>> range(10)' '[0,1,2,3,4,5,6,7,8,9]' (source:http: /docs.python.org/release/1.5.1p1/tut/range.html)下面是3.3的「範圍」鏈接 - http://docs.python.org/3.3/library/stdtypes.html?highlight=range #範圍 – harperville 2013-10-31 12:01:38

3

一點題外話,但:

for i in temp.keys(): 
    key = i 
    num = [int(frequency[key])] 
    tvalues += num 

should just be: 

tvalues = temp.values() 

例如:

>>> D = {'a':1, 'b':2, 'c':3, 'd':4} 
>>> D.keys() 
['a', 'c', 'b', 'd'] 
>>> D.values() 
[1, 3, 2, 4] 
>>> D.items() 
[('a', 1), ('c', 3), ('b', 2), ('d', 4)] 
>>> 

,它看起來像你的代碼可以改成這樣:

>>> D = {'a':1, 'b':2, 'c':3, 'd':4} 
>>> def get_top_k(D, k): 
...  return sorted(D.items(), reverse=True, key=lambda x: x[1])[:k] 
... 
>>> get_top_k(D, 2) 
[('d', 4), ('c', 3)] 
>>> 
相關問題