无法从列表理解中获得所需的输出

Failing to get required output from list comprehension

我正在开发一个程序来确定选举中的选票是否有效并计算选票以找到获胜者。预先警告,我对 python 和一般编码还很陌生。

目前,我正在从逗号分隔的文本文件中读取选票 - 每行都是一张选票,选票中的每张选票都需要检查有效性,其中有效选票是任何正整数,并且有与候选人相同的票数(有 5 名候选人)。投票将由另一个函数标准化。

还有一个函数可以将候选人姓名读入列表——计票时投票索引与候选人索引匹配。用于确定有效性的规则有一些例外情况,例如,该候选人的选票上的空白票将转换为零票,而超过 5 票的选票将被完全忽略。

这是读取选票的代码部分。

def getPapers(f, n):

x = f.readlines() #read f to x with \n chars
strippedPaper = [line.strip("\n") for line in x] #stores ballot without \n chars. 
print(strippedPaper)#print without \n chars
print()

strippedBallot = [item.replace(' ', '') for item in strippedPaper] #remove whitespace in ballots
print(strippedBallot) #print w/out white space
print()

#Deal with individual ballots
m = -1
for item in strippedBallot:
    m += 1
    singleBallot = [item.strip(',') for item in strippedBallot[m]]

    print(singleBallot)

getPapers(open("testfile.txt", 'r'), 5)

testfile.txt

的内容
1,2, 3, 4

,23,
9,-8
these people!
4,    ,4,4
5,5,,5,5

这是输出

#Output with whitespace.
['1,2, 3, 4 ', '', ', 23, ', '9,-8', 'these people!', '4,    ,4,4', '5,5,,5,5']

#Output with whitespace removed.
['1,2,3,4', '', ',23,', '9,-8', 'thesepeople!', '4,,4,4', '5,5,,5,5']

#Output broken into single ballots by singleBallot.
['1', '', '2', '', '3', '', '4']
[]
['', '2', '3', '']
['9', '', '-', '8']
['t', 'h', 'e', 's', 'e', 'p', 'e', 'o', 'p', 'l', 'e', '!']
['4', '', '', '4', '', '4']
['5', '', '5', '', '', '5', '', '5']

每张选票都将传递给另一个功能,以检查有效性和规范化。问题是每张选票在输出后被格式化的方式,例如 ['1,2,3,4'] 被转换为 ['1', '', '2', '', '3', '', ' 4'] - 第一个问题是如何在不创建空格的情况下从列表中删除逗号?检查选票时将计算这些空格,并且选票将无效,因为它有得票多于候选人! (空格转换为零票)。

其次,,['', '2', '3', ''] 需要读作 ['', '23', ''] 或者它将计数 0、2、3、0 而不是 0、23、0,最终的计票结果将是错误的,并且 ['9', '', '-', '8'] 应该读作 ['9' , '', '-8'] 或 '-', '8' 将读作两票而不是一票 -8 的无效票。

有没有比我用来检索逗号分隔项的方法更好的方法,它不会创建空格和错误地分解列表项?

假设您的输入文件如下:

-bash-4.1$ cat testfile.txt
1,2, 3, 4
, 23,
9,-8
these people!
4,    ,4,4
5,5,,5,5

你的程序简化了一点:

def getPapers(f):
    x = f.readlines() #read f to x with \n chars
    strippedPaper = [line.strip("\n") for line in x] #stores ballot without \n chars. 
    print(strippedPaper)#print without \n chars
    print()

    strippedBallot = [item.split(",") for item in strippedPaper] #remove whitespace in ballots
    print(strippedBallot) #print w/out white space
    print()

    for item in strippedBallot:
        print(item)

getPapers(open("testfile.txt", 'r'))