TypeError:'int'对象不可迭代。为什么我会收到此错误?请帮忙

时间:2011-04-28 17:49:49

标签: python

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

4 个答案:

答案 0 :(得分:6)

也许你的意思是

for i in range(kk):

答案 1 :(得分: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)]
>>> 

答案 2 :(得分:2)

您有for i in kkkk只是一个整数。你不能迭代一个整数,你只能迭代序列/迭代。

如果你想从0迭代到for i in range(kk),你可能想要(kk-1)

答案 3 :(得分:1)

因为kk = int(k)

kk只是一个数字,而不是数字数组

你想做什么,让我们帮你修理它?