从文件中解析数据(使用Python):如何确定第114届国会中共和党、民主党和独立党籍议员的人数

2024-09-30 18:34:33 发布

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

所以,我一直在研究这段代码,以确定第114届国会中共和党、民主党和无党派参议员的人数。这是我的密码。由于某些原因,我不断得到关于我的变量,以num开头的奇怪的错误。请帮助。你知道吗

def main():
    # Determines the number of senators of each party affiliation
    infile = open("Senate114.txt", 'r')
    set1 = {line.rstrip() + "\n" for line in infile}
    infile.close()
    listx = list(set1)
    listx.sort(key=lambda x: x.split(',')[2])  # sort by party affiliation
    partyAffiliation = listx[2]
    rep = []
    dem = []
    ind = []
    numRep = []
    numDen = []
    numInd = []
    while (partyAffiliation == 'R'):
        rep = rep.expend
        numRep == int(len(rep))
    while (partyAffiliation == 'D'):
        dem = dem.extend
        numDem == int(len(dem))
    while (partyAffiliation == 'I',):
        ind = ind.extend
        numInd == int(len(ind))

    print('Party Affiliation: ')
    print('Republicans: ',numRep)
    print('Democrats:' ,numDem)
    print('Independents:' ,numInd)

main()

Tags: oflenmainpartyinfileintprintind
1条回答
网友
1楼 · 发布于 2024-09-30 18:34:33

假设数据与此相似:

Gooding,Cuba,R
Miller,Dennis,D
Bolton,Michael,I
Grouch,Oscar,I
Einstein,Albert,R
Azaria,Hank,D
Motzart,Amadeus,I

您可以使用如下代码:

import collections

lines = open("Senate114.txt").read().splitlines()
parties = [line.split(",")[2] for line in lines]
party_counts = collections.Counter(parties)

print(party_counts)

输出

Counter({'I': 3, 'R': 2, 'D': 2})

您可以添加:

print('Party Affiliations: ')
print('Republicans:', party_counts.get('R', 0))
print('Democrats:', party_counts.get('D', 0))
print('Independents:', party_counts.get('I', 0))

相关问题 更多 >