gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:40 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com