返回后继续迭代子列表?

时间:2017-09-22 04:56:26

标签: python python-3.x list return list-comprehension

我正在尝试遍历列表列表中的值,以查看最里面的值是否遵循某些规则:

  • 空白列表返回([],'空白')
  • 带有负整数,浮点数或字符串的列表返回([],'非数字')
  • 列出正整数组合并按原样返回。
问题是,在返回子列表中的第一个值之后,程序跳过该子列表中的所有其他值并转到下一个值,进一步查看当前输出以查看我的意思

    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对应返回“非数字”,因为它包含负数。

逐步完成后,我发现该函数只返回每个子列表中的第一个值。

我需要的是是让程序再次通过相同的子列表并在确定子列表是否有效之前检查每个值 - 我不确定如何检查每个子列表值和THEN确定该子列表的全部内容是否有效。

2 个答案:

答案 0 :(得分:0)

我认为我找到了解决我自己问题的方法,可能会遇到任何人:

通过检查并将递交给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], '')

答案 1 :(得分:0)

这是一个较短的版本,如果它会有所帮助。如果我能正确理解你的问题,我希望这会有所帮助。基本上,你可以在一个功能中做所有事情,而不是做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