gpt4 book ai didi

python - 使用 dict 嵌套 for 循环

转载 作者:行者123 更新时间:2023-12-01 04:04:01 26 4
gpt4 key购买 nike

我正在做 Coursera python 练习,但在编写代码时遇到问题。

问题如下:

Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail.

The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.

示例文本文件位于此行: http://www.pythonlearn.com/code/mbox-short.txt

预期输出应该是:

cwen@iupui.edu 5

这是我的代码:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
count = dict()

for line in handle:
word = line.split()
if line.startswith('From '):
email = word[1]
for sender in email:
if sender not in count:
count[sender] = count.get(sender, 0) + 1

bigcount = None
bigname = None
for name,count in count.items():
if bigname is None or count > bigcount:
bigname = name
bigcount = count
print bigname, bigcount

我的输出是:

. 1

我认为“电子邮件中的发件人”部分有问题,但无法弄清楚它如何导致不需要的输出。

最佳答案

以下循环在这种情况下不合适,因为您基本上是在迭代电子邮件地址的所有字符。

for sender in email:
...

这就是为什么当您打印数量最多的电子邮件地址时,您会得到一个字符.。在循环末尾打印计数后,您可以轻松查看效果。

以下检查也是多余的,因为当您使用 get 方法获取字典值时,您会隐式检查它。

if sender not in count:
...

所以,最终修正后的代码应该是这样的。

name = raw_input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
count = dict()

for line in handle:
word = line.split()
if line.startswith('From '):
count[word[1]] = count.get(word[1], 0) + 1
largest = 0
email = ''
for k in count:
if count[k] > largest:
largest = count[k]
email = k
print largest, email

关于python - 使用 dict 嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35977103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com