为什么我的 for 循环没有将所有值添加到字典中?
def biggest_family(fil):
with open(fil) as file:
name = {}
ans = {}
text = file.read().split("\n")
for i in range (0 , len(text)-1):
first = text[i].split()
name[first[0]] = first[1]
for b in name:
if name[b] in ans:
ans[name[b]] += 1
else:
ans[name[b]] = 1
print(ans)
输出应为家庭的姓氏的字典,并且是列表中存在的次数。由于某种原因,它对某些数据集非常有效,而其他数据集则是一个数字。如您在下面的图片中所看到的,它在第一个测试中以正确的数量打印了辛普森一家和格里芬斯,但在其上方的兰尼斯特家族中没有打印出来。
def biggest_family(fil):
with open(fil) as file:
name = {}
ans = {}
text = file.read().split("\n")
for i in range (0 , len(text)-1):
first = text[i].split()
name[first[0]] = first[1]
for b in name:
if name[b] in ans:
ans[name[b]] += 1
else:
ans[name[b]] = 1
print(ans)
The output should be a dictionary of the last name of the family and amount of times it is present in the list. For some reason it works perfectly for some datasets and is short a number on others. As you can see in the picture below it prints the simpsons and griffins in the correct amount but not the Lannister family above it in the first test.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是
Cersei Smith
在您的第一个循环中的名称
字典中替换cersei lannister
。无法重复字典键,因此您不能有两个不同的cersei
条目。不需要
name
字典,只需在该循环中创建ans
字典即可。The problem is that
Cersei Smith
replacesCersei Lannister
in thename
dictionary in your first loop. Dictionary keys can't be repeated, so you can't have two differentCersei
entries.There's no need for the
name
dictionary, just create theans
dictionary in that loop.您的问题似乎表明输出应该是打印文本而不是字典。毫无疑问,有一些无法理解的理解可以用更少的代码来完成此操作,但让我们采取逐步的方法:
我创建了一个名为 family.txt 的文件,其中包含您问题中显示的内容。其输出将是:
Your question seems to indicate that the output should be printed text rather than a dictionary. There are undoubtedly some impossible to understand comprehensions that will do this with less code but let's take a step-wise approach:
I've created a file called family.txt with the content shown in your question. The output of this will be: