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

新手上路,请多包涵

我正在尝试调用一个函数,该函数将清空我作为参数发送的两个列表。我如何着手清空函数内的列表,并确保一旦代码开始在 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()

原文由 Ethan Venencia 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 974
2 个回答

使用 namelist.clear() 清除列表

原文由 Stephie 发布,翻译遵循 CC BY-SA 3.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()

不确定为什么你会竭尽全力得到 [], [] 但不管你的船是什么。


查看代码上的注释,以更好地了解我进行更改的原因。

原文由 Ma0 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题