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)