我已经为此工作了两天。这是作业中的内容:
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/