为什么我的 for 循环没有将所有值添加到字典中?

发布于 2025-01-19 22:13:55 字数 736 浏览 2 评论 0原文

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.

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

强者自强 2025-01-26 22:13:55

问题是Cersei Smith在您的第一个循环中的名称字典中替换cersei lannister。无法重复字典键,因此您不能有两个不同的cersei条目。

不需要name字典,只需在该循环中创建ans字典即可。

def biggest_family(fil):
    with open(fil) as file:
        text = file.read().split("\n")
    ans = {}
    for full_name in text[:-1]:
        first_name, last_name = full_name.split()
        if last_name in ans:
            ans[last_name] += 1
        else:
            ans[last_name] = 1   
    print(ans)

The problem is that Cersei Smith replaces Cersei Lannister in the name dictionary in your first loop. Dictionary keys can't be repeated, so you can't have two different Cersei entries.

There's no need for the name dictionary, just create the ans dictionary in that loop.

def biggest_family(fil):
    with open(fil) as file:
        text = file.read().split("\n")
    ans = {}
    for full_name in text[:-1]:
        first_name, last_name = full_name.split()
        if last_name in ans:
            ans[last_name] += 1
        else:
            ans[last_name] = 1   
    print(ans)
也只是曾经 2025-01-26 22:13:55

您的问题似乎表明输出应该是打印文本而不是字典。毫无疑问,有一些无法理解的理解可以用更少的代码来完成此操作,但让我们采取逐步的方法:

def biggest_family(fil):
    with open(fil) as family:
        d = dict() # empty dictionary
        hi_count = 0 # keep track of the hi number of family members
        for line in map(str.strip, family): # iterate of the file line by line
            forename, surname = line.split() # get the surname and forename
            d.setdefault(surname, []).append(forename) # append to a list value against a surname key in the dictionary
            if (l_ := len(d[surname])) > hi_count: # check the hi count
                hi_count = l_
        output = [] # empty list
        for k, v in d.items(): # iterate over the dictionary looking for families equal to the hi count
            if len(v) == hi_count: # we're interested in this one
                output.append(f'{k} family: {" ".join(sorted(v))}')
        for line in sorted(output): # looks like the output needs to be sorted
            print(line)

biggest_family('family.txt')

我创建了一个名为 family.txt 的文件,其中包含您问题中显示的内容。其输出将是:

Lannister family: Cersei Jaime Tyrion
Stark family: Arya Catelyn Ned

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:

def biggest_family(fil):
    with open(fil) as family:
        d = dict() # empty dictionary
        hi_count = 0 # keep track of the hi number of family members
        for line in map(str.strip, family): # iterate of the file line by line
            forename, surname = line.split() # get the surname and forename
            d.setdefault(surname, []).append(forename) # append to a list value against a surname key in the dictionary
            if (l_ := len(d[surname])) > hi_count: # check the hi count
                hi_count = l_
        output = [] # empty list
        for k, v in d.items(): # iterate over the dictionary looking for families equal to the hi count
            if len(v) == hi_count: # we're interested in this one
                output.append(f'{k} family: {" ".join(sorted(v))}')
        for line in sorted(output): # looks like the output needs to be sorted
            print(line)

biggest_family('family.txt')

I've created a file called family.txt with the content shown in your question. The output of this will be:

Lannister family: Cersei Jaime Tyrion
Stark family: Arya Catelyn Ned
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文