【问题标题】:How to exclude "0" from the output when the user enters it?用户输入时如何从输出中排除“0”?
【发布时间】:2023-04-04 21:44:01
【问题描述】:

这是我目前所拥有的:

# Read input names from user until 0, print input
inputNames = []
names = ""
while names != "0":
    names = input("Please enter a name or enter '0' to quit: ")
    inputNames.append(names)
    if names == "0":
        del inputNames[3]
print("\n".join(inputNames))

这只是一个快速修复,因为当用户输入“0”以打印列表时,我无法弄清楚如何从输出中排除“0”。所以它应该向数组输入名称,直到输入“0”,然后按每行的输入顺序打印数组减去“0”输入。只要输入 3 个名称,我的就可以工作。

【问题讨论】:

  • 抱歉,我不明白 - 您的问题是什么?当您尝试运行代码时发生了什么,这与应该发生的有什么不同?
  • 当用户输入0 时,它将显示在屏幕上,因为input() 就是这样工作的。如果要删除列表中的最后一个元素,请使用del inputNames[-1]

标签: python arrays input


【解决方案1】:

在添加到列表之前检查 0:

inputNames = []
while 1:
    name = input("Please enter a name or enter '0' to quit: ")
    if name == '0':
        break
    inputNames.append(name)
print('\n'.join(inputNames))

【讨论】:

    【解决方案2】:

    在 while 循环之后放置“inputNames.pop()”或“inputNames.remove('0')”以删除零。

    【讨论】:

    • 谢谢,这让我想到了一些我没有想到的东西,使用 remove!
    • # 从用户读取输入名称直到 0,打印 input inputNames = [] names = "" while names != "0": names = input("请输入名称或输入 '0' quit: ") inputNames.append(names) if names == "0": inputNames.remove("0") print("\n".join(inputNames))
    • 另外,您不需要“if names == 0:”,因为如果 names 等于 0,while 循环已经设置为结束。然后你可以从while循环外的列表中删除0。
    猜你喜欢
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2017-10-13
    • 2011-02-23
    相关资源
    最近更新 更多