【问题标题】:last list item appears in new list after adding and添加后最后一个列表项出现在新列表中,并且
【发布时间】:2017-06-12 00:47:17
【问题描述】:

我正在学习 Python,但遇到了这段代码的问题。我正在使用 for 循环在列表中循环,我需要它在最后一项之前打印单词'and'。我已经让它工作了,但不是我想要的方式。

当我打印时,'and ' + last item 不会出现在列表中,而是出现在列表之外。有人可以告诉我我做错了什么吗?

listToPrint = []
while True:
    newWord = input("Enter a word to add to the list (press return to stop adding words) > ")
    if newWord == "":
        break
    else:
        listToPrint.append(newWord)
for i in range(1):
    print(listToPrint[0:-1], end =', ' + 'and ' + listToPrint[-1])

【问题讨论】:

  • 列表的切片返回一个列表。 listToPrint[0:-1] 是一个列表,所以右方括号出现在 ',' 之前,如果这就是你的意思。
  • 我认为这就是正在发生的事情,但我不知道如何解决这个问题。

标签: python list python-3.x


【解决方案1】:

您可以简单地 str.join() 删除最后一个单词并打印最后一行:

print("{}, and {}".format(", ".join(listToPrint[:-1]), listToPrint[-1]))

【讨论】:

  • 我做了一个小改动 print("{}, and {}".format(", ".join(listToPrint[:-1]), listToPrint[-1])),但是这个是我正在寻找的。你能解释一下这段代码或告诉我在哪里可以了解这是什么吗?
  • @KennyFreeman - 你也可以使用你的原始声明:print(", ".join(listToPrint[:-1]), end=", and " + listToPrint[-1] + "\n") ,但是(意见时间)最好尽可能控制你的输出格式,我找到了反正更具可读性。
  • 我喜欢你最初的做法。我只是不知道您可以像使用字符串那样进行格式化。那叫什么?
  • @KennyFreeman - str.format() 是在 Python 中进行复杂字符串格式化的原生方式和首选方式。您可以在Format String Syntax 阅读有关其使用的更多信息
【解决方案2】:

以下代码可以满足您的需求。

listToPrint = []
while True:
    newWord = input("Enter a word to add to the list (press return to stop adding words) > ")
    if newWord == "":
        break
    else:
        listToPrint.append(newWord)
listToPrint[-1] = "and " + listToPrint[-1]

print(listToPrint)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    相关资源
    最近更新 更多