字典有问题吗

2024-06-26 00:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

这个函数的思想是将一个文件作为输入。这个档案里有政客和他们各自的党派。独立党是1,共和党是2,民主党是3,未知党是4。必须返回的是各方代表的次数。你知道吗

档案中有独立党6人,共和党16人,民主党22人,不为人知的6人。 输出应该如下所示。你知道吗

独立6

共和国16

民主党人22

未知6

但我所拥有的是

4.6条

3月22日

2月16日

16岁

我不知道怎么把代表当事人的数字改成实际当事人的名字。你知道吗

def polDict(s1):
        infile=open(s1,'r')
        content=infile.read()
        counters={}
        party='1234'
        wordList = content.split()
        for i in wordList:
            if i in party:
                if i in counters:
                    counters[i]+=1
                else:
                    counters[i]=1
        for i in counters:              

            print('{:2} {}'.format(i,counters[i]))

Tags: 函数inforifparty代表档案content
2条回答

关于文件的外观,您没有提供太多的信息;也就是说,由于所提供的信息有限,如果我正确理解了您的代码,那么您需要做的是定义一个包含参与方名称及其各自编号的字典,然后编辑print语句,以打印对应于i的参与方名称,而不是i本身:

def polDict(s1):
    infile=open(s1,'r')
    content=infile.read()
    counters={}
    party='1234'
    party_names = {1:'Independent', 2:'Republican', 3:'Democrat', 4:'Not known'}
    wordList = content.split()
    for i in wordList:
        if i in party:
            if i in counters:
                counters[i]+=1
            else:
                counters[i]=1
    for i in counters:              
        print('{:2} {}'.format(party_names[i], counters[i]))

您忘记关闭open(),这是使用with块的众多原因之一。总之,我假设这是输入文件的样式:

Clinton 3
Cruz 2
Sanders 3
Trump 2
Dutter 1

您希望输出为:

Republican 2
Democratic 2
Independent 1

如果这是不正确的,那么这个函数应该改变,以完全适合你想要的。你知道吗

from collections import defaultdict

def getCandidates(infile):
    parties = {1: "Independent", 2: "Republican", 3: "Democratic", 4: "Unknown"}
    candidates = defaultdict(int)
    with open(infile, "r") as fin:
        for line in fin:  # assuming only 2 columns and the last column is the number
            candidates[parties[int(line.split()[-1])]] += 1
    for party, count in candidates.items():  #.iteritems() in python 2.7
        print("{} {}".format(party, count))

getCandidates("test.txt")

相关问题 更多 >