如何在python中返回一个空列表

时间:2017-11-15 17:34:13

标签: python python-3.x

我正在尝试调用一个函数来清空我作为参数发送的两个列表。 我如何清空函数中的列表并确保它们在代码在Python的原始函数中重用它们时是空的?下面是我用作更大系统的测试运行的代码。

def Input():
    nextRound = ['Dad', 'Mom']
    maleNames = ['son', 'James', 'Mick', 'Dad']

    a = int(input('Enter a number please'))
    if a == 1:
        ErrorInput(1, nextRound, maleNames )
        # I want the below to print two empty strings
        print(nextRound, maleNames)

def ErrorInput(error, namelist, round):


    if error == 1:
        print('ERROR: You have entered a number above what is impossible to 
        score')
        namelist = []
        round = []
    elif error == 2:
        print('ERROR: You Have entered a score meaning both players win')
        namelist = []
        round = []
    elif error == 3:
        print('ERROR: You have entered a score meaning neither of the two 
        players win')
        namelist = []
        round = []
    elif error == 4:
        print('EEROR: You have entered a negative number, this is 
        impossible')
        namelist = []
        round = []

    return(namelist, round)

Input()

3 个答案:

答案 0 :(得分:0)

在这里,我冒昧地整理了代码。

def start():  # don't use the name input()
    nextRound = ['Dad', 'Mom']
    maleNames = ['son', 'James', 'Mick', 'Dad']

    a = int(input('Enter a number please'))
    if a == 1:
        nextRound, maleNames = ErrorInput(1, nextRound, maleNames)  # if you want nextRound, maleNames to be [] you have to assign it to them
        print(nextRound, maleNames)

def ErrorInput(error, namelist, round):
    error_codes = {1: 'ERROR: You have entered a number above what is impossible to score', 2: 'ERROR: You Have entered a score meaning both players win',3: 'ERROR: You have entered a score meaning neither of the two players win', 4: 'ERROR: You have entered a negative number, this is impossible'}  # too many ifs makes one wonder if a dictionary is the way to go
    print(error_codes.get(error, 'Unknown Error'))
    return([], [])  # return the empty lists.

start()

不知道为什么你会这么长,只能得到[], [],但无论你的船是什么漂浮。

看看代码上的注释,以便更好地了解我为何进行更改。

答案 1 :(得分:0)

使用namelist.clear()清除列表

答案 2 :(得分:0)

根据上述评论,我不会遵循您的代码。但要迭代清空列表,请尝试:

while len(maleNames) !=0:
    popped = maleNames.pop()
    print('Popped value: ', popped, '\tNew list: ', maleNames)