返回后继续通过子列表进行迭代



我正在尝试通过列表列表中的值迭代,以查看最内在的值是否遵守某些规则:

  • 空白列表返回([],'空白')
  • 列出了负整数,浮点或字符串返回([],'nontigits')
  • 列出了积极整数的组合,并按原样返回。

问题是,在返回子列表中的第一个值之后,该程序跳过该子列表中的所有其他值,然后转到下一个值,请进一步查看当前的输出,以查看我的意思。

    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']], '')

前两行很好,它是空白的,返回空白,接下来的两行 fix,因为它按原样返回值,但是第三对不应返回([],空白),因为输入包含正整数。您还可以看到第四对应返回"非数字",因为它包含一个负数。

逐步进行后,我发现该函数仅返回每个子列表中的第一个值。

我需要的是让程序再次通过同一子列表并在确定子列表是否有效之前检查每个值 - 我不确定如何检查每个值子列表值,然后确定该子列表的整个内容是否使其有效。

我想我已经为可能遇到的任何人找到了解决我自己的问题的解决方案:

通过检查并附加将每张投票交给ParseVote()到新列表中,然后将新列表的列表转回Parsepaper(),我已经能够进行我需要的调整。

现在,包含文本或否定数字的选票自动无效,并且投票加起来为零或被认为是空白的。

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) #print returned value

    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 (voteWorth, "") 
    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:
        voteWorthList = []
        for i in s:
            if i == ' ':
                i = 0
                voteWorthList.append(i)
                #return int(0) #for empty spaces, return to parsePaper
            elif i == '':
                i = 0
                voteWorthList.append(i)
                #return int(0) #for blanks, return to parsePaper
            elif i.isdigit() == False: #for non-digits
                i = int(-1)
                voteWorthList.append(i)
                #return int(-1) #return to parsePaper
            elif int(i) < 0: #for negnative numbers
                i = int(-1)
                voteWorthList.append(i)
                #return int(-1) #return to parsePaper
            else:
                i = int(i)
                voteWorthList.append(i)
                #return int(i) #return the positive integer to parsePaper
        print(voteWorthList)
        for i in voteWorthList:
            if i < 0:
                return int(-1)
        if sum(voteWorthList) == 0:
                return 0
        else:
            return voteWorthList
    except ValueError:
            print("The object passed to parseVote is invalid.")

新输出就是这样,显示了原始输入,调整后的输入和最终输出:

['']
[0]
([], 'blank')
['1', '2', '3', '4']
[1, 2, 3, 4]
([1, 2, 3, 4], '')
['', '23', '']
[0, 23, 0]
([0, 23, 0], '')
['9', '-8']
[9, -1]
([], 'non-digits')
['thesepeople!']
[-1]
([], 'non-digits')
['4', '', '4', '4']
[4, 0, 4, 4]
([4, 0, 4, 4], '')
['5', '5', '', '5', '5']
[5, 5, 0, 5, 5]
([5, 5, 0, 5, 5], '')

这是一个较短的版本,如果有帮助。我希望如果我正确理解您的问题,这会有所帮助。基本上,您可以在一个功能中完成所有操作,而不是制作3

def getPapers(f, n):
    x = f.readlines()
    strippedPaper = [line.strip("n").replace(' ', '') for line in x]
    ballot = tuple()
    allBlanks = False if [i.strip() for i in strippedPaper if i] else True
    if allBlanks:
        ballot = ([], "blank")
    elif len(strippedPaper) > n:
        ballot = ([], "too long")
    else:
        ballot = (strippedPaper, "")
        for i in strippedPaper:
            if i.strip() == '':
                continue 
            if not i.isdigit() or int(i) < 0:
                ballot = ([], "non-digits")
                break
    return ballot

最新更新