python - 打印以逗号分隔的项目列表,但在最后一项之前使用单词 "and"

标签 python list python-3.x loops for-loop

我已经为此工作了两天。这是作业中的内容:

Say you have a list value like this: listToPrint = ['apples', 'bananas', 'tofu', 'cats'] Write a program that prints a list with all the items separated by a comma and a space, with "and" inserted before the last item. For example, the above list would print 'apples, bananas, tofu, and cats'. But your program should be able to work with any list not just the one shown above. Because of this, you will need to use a loop in case the list to print is shorter or longer than the above list.

这是我目前所拥有的:

listToPrint = []
while True:
    newWord = input("a, b, and c ")
    if newWord == "":
        break
    else:
        listToPrint.append(newWord)

最佳答案

您显示的代码似乎解决了与您的作业要求您解决的问题不同的问题。作业的重点是打印提供的列表中的值,而您的代码是关于输入用户的项目并将它们放入成一个列表。先做一个再做另一个可能有意义,但对于您在评论中给出的作业,input 代码是完全不相关的。

下面是我解决该作业的方法(可能使用您还不理解的代码):

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

更“新手友好”的方法看起来更像这样:

for item in list_to_print[:-1]:
    print(item, end=', ')
print('and', list_to_print[-1])

关于python - 打印以逗号分隔的项目列表,但在最后一项之前使用单词 "and",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39782689/

相关文章:

python - 使用 elasticsearch-dsl-py 在另一个字段中包含的字段上创建术语查询

python - 停止在 pydub 中播放音频

java - 在添加到两个暗列表之前,使用 java 中的 contains 来检查重复项

python-3.x - PyGame,等待计算机决定它的 Action

Python - 图像处理和光学字符阅读器

python - 如果循环为空则显示一条消息

python - SQL 数据库是否比大型 Pandas 数据框的内存/性能效率更高?

python - 如何在Python列表中交换列表中的项目

python - 如何在排除一种可能性的情况下随机选择列表中的项目?

python-3.x - 仅当引号包含 3 个或更多字符时才拆分