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
Perhaps you meant
for i in range(kk):
a bit off topic, but:
for i in temp.keys():
key = i
num = [int(frequency[key])]
tvalues += num
should just be:
tvalues = temp.values()
example:
>>> 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)]
>>>
and it looks like your code could be changed to this:
>>> 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)]
>>>
You have for i in kk
and kk
is just an integer. You can't iterate over an integer, you can only iterate over a sequence/iterable.
You probably want for i in range(kk)
if you want to iterate from 0 to (kk-1)
.
Because kk = int(k)
kk
is only one single number, not an array of numbers
What are you trying to do, for us to help you fixing it?
精彩评论