如何添加'和'在列表元素的末尾
num = [1,2,3,4]。
假设我有一个名为“ num”的列表。
我想以这种方式打印列表:1、2、3和4。
最终如何添加“和”?
num = [1, 2, 3, 4].
Suppose I have a list named 'num'.
I want to print the list this way: 1, 2, 3, and 4.
How do I add 'and' at the end like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python中的正常方式将逗号(例如逗号)插入字符串列表中的正常方式是使用
join> join()
:但是您想要和在最后一个逗号之后:
The normal way in Python to insert delimiters like a comma into a list of strings is to use
join()
:but you want and after the last comma:
我建议您使用python的
enumerate()
函数。您可以在此处阅读更多有关它的信息: https:///docs.python.org/ 3/library/functions.html#枚举这使我们可以迭代列表,但同时跟踪索引。这很有用,因为当索引显示我们处于列表的最后一个元素时,这意味着我们的索引是在
len(num)-1
的它(以及其背后的一个完整停止,这就是您的示例中所示
的
。
I'd suggest you to use python's
enumerate()
function. You can read more about it here: https://docs.python.org/3/library/functions.html#enumerateThis allows us to iterate through the list, but simultaneously keeping track of the index. This is useful because, when the index shows that we are at the last element of the list, which means our index is at
len(num)-1
, we should output an "and" in front of it (and a full stop.
behind it, which is what is shown in your example.You could do something like this:
This yields the output:
1, 2, 3, and 4.