小编Reb*_*oel的帖子

索引打印元组[:1]有效,但[0]产生TypeError

fhand = open(raw_input('Enter a file name: '))
counts = dict()
words = []
for lines in fhand:
    if lines.startswith('From') and not lines.startswith('From:'):
        words = lines.split()
        if words[1] not in counts:
            counts[words[1]] = 1
        else:
            counts[words[1]] += 1

lst = list()
for key, val in counts.items():
    lst.append((val, key))
lst.sort(reverse=True)
for key, val in lst[0]:
    print key, val
Run Code Online (Sandbox Code Playgroud)

有问题的部分是:

for key, val in lst[0]:
    print key, val
Run Code Online (Sandbox Code Playgroud)

这给了我:TypeError:'int'对象不可迭代.我已经发现,由于某种原因,这确实有效:

输入:

for key, val in lst[:1]:
    print key, val
Run Code Online (Sandbox Code Playgroud)

输出:

Enter a file name: …
Run Code Online (Sandbox Code Playgroud)

python indexing tuples python-2.7

2
推荐指数
1
解决办法
62
查看次数

标签 统计

indexing ×1

python ×1

python-2.7 ×1

tuples ×1