我試圖通過值列表的列表迭代,看看最裏面的值遵守一定的規則:返回後繼續遍歷子列表嗎?
- 空白列表返回([],「空白」)
- 名單負整數,浮點數,或字符串返回([],'非數字')
- 列表與正整數和返回的組合。
問題是,在返回子列表中的第一個值之後,程序將跳過該子列表中的所有其他值,然後轉到下一個值,查看當前輸出以進一步查看我的意思是。
def getPapers(f, n):
x = f.readlines() #read f to x with \n chars and whitespace
strippedPaper = [line.strip("\n").replace(' ', '') for line in x] #stores formatted ballot
#print(strippedPaper)
print()
#Create list of lists from ballots.
strippedBallot = [item.split(",") for item in strippedPaper]
#print(strippedBallot)
print()
#Information passed to parsePaper
try:
for ballot in strippedBallot:
print(ballot) #Show individual ballots
valueParsePaper = parsePaper(ballot, n) #ballot is passed to parsePaper here.
print(valueParsePaper) #Displays the value returned from parsePaper
except TypeError:
print("There was an error with the data type passed to var 'valueParsePaper'\n"
"from this set.\n")
def parsePaper(s, n):
#If s is informal reutrn an empty list with an appropriate string
try:
if len(s) > n:
tooLong = ([], "too long")
return tooLong
elif len(s) == 0:
blankBallot = ([], "blank")
return blankBallot
#elif sum(s[:]) == 0:
#blankBallot = ([], "blank")
#return blankBallot
else:
voteWorth = parseVote(s)
#The vote inside the ballot is passed to parseVote
#parseVote returns a value to voteWorth.
if voteWorth == 0: #for empty/blank string
return ([], "blank")
elif voteWorth == int(-1): #for non-digits/invalid numbers
return ([], "non-digits")
else: #for valid votes
return ([s], "")
except ValueError:
print("There is an invalid value at parsePaper")
#parseVote(s) Returns vote from s, return 0 for empty vote, -1 for votes containing non-digits
#except spaces
def parseVote(s):
try:
for i in s:
if i == ' ':
return int(0) #for empty spaces, return to parsePaper
elif i == '':
return int(0) #for blanks, return to parsePaper
elif i.isdigit() == False: #for non-digits
return int(-1) #return to parsePaper
elif int(i) < 0: #for negnative numbers
return int(-1) #return to parsePaper
else:
return int(i) #return the positive integer to parsePaper
except ValueError:
print("The object passed to parseVote is invalid.")
這表明在對所述輸入和輸出。
['']
([], 'blank')
['1', '2', '3', '4']
([['1', '2', '3', '4']], '')
['', '23', '']
([], 'blank')
['9', '-8']
([['9', '-8']], '')
['thesepeople!']
([], 'non-digits')
['4', '', '4', '4']
([['4', '', '4', '4']], '')
['5', '5', '', '5', '5']
([['5', '5', '', '5', '5']], '')
前兩行是細,它是空白,並返回出現很好,因爲它返回值作爲空白,接下來的兩行,但所述第三對不應該返回([],空白),因爲輸入包含正整數。你也可以看到第4對應該返回'非數字',因爲它包含一個負數。
經過一步一步,我發現該函數只返回每個子列表的第一個值。
我需要什麼是程序再次通過相同的子列表,檢查每一個價值判斷之前,如果一個子表是有效的 - 我不能確定如何檢查每個子列表值然後確定該子列表的全部內容是否有效。
請提供[mcve]。你的代碼包含很多不相關的部分。以示例輸入和示例輸出開始,然後在示例中重現您的錯誤。 –
感謝您的閱讀,對不起,我無法提供一個更簡單的例子來解決這個問題。我相信我現在已經解決了我自己的問題,所以我在下面分享我的答案。 –