0

我正在制定一個計劃,以確定選舉投票是否有效,並計算投票數以找到勝者。預警,我對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票的無效投票。

是否有更好的方法比我用於檢索逗號分隔的項目,它不會創建空的空間和錯誤地分解列表項目?

+0

您TESTFILE.TXT的內容添加到這個問題。 –

+0

當然。我在輸入和輸出部分之間添加了它。 –

回答

0

假設你的輸入文件如下:

-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')) 
+0

這似乎有所幫助,現在輸出的格式會更容易檢查有效性。 –

+0

@CamAtkinson如果您發現您正在尋找的東西,請將您的問題標記爲已回答。 –