如何添加'和'在列表元素的末尾

发布于 2025-02-04 04:23:36 字数 89 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怀中猫帐中妖 2025-02-11 04:23:36

Python中的正常方式将逗号(例如逗号)插入字符串列表中的正常方式是使用join> join()

>>> ", ".join(str(x) for x in num)
'1, 2, 3, 4'

但是您想要在最后一个逗号之后:

>>> prefix, _, suffix = ", ".join(str(x) for x in num).rpartition(" ")
>>> print (prefix,"and",suffix)
1, 2, 3, and 4

The normal way in Python to insert delimiters like a comma into a list of strings is to use join():

>>> ", ".join(str(x) for x in num)
'1, 2, 3, 4'

but you want and after the last comma:

>>> prefix, _, suffix = ", ".join(str(x) for x in num).rpartition(" ")
>>> print (prefix,"and",suffix)
1, 2, 3, and 4
﹏雨一样淡蓝的深情 2025-02-11 04:23:36

我建议您使用python的enumerate()函数。您可以在此处阅读更多有关它的信息: https:///docs.python.org/ 3/library/functions.html#枚举

这使我们可以迭代列表,但同时跟踪索引。这很有用,因为当索引显示我们处于列表的最后一个元素时,这意味着我们的索引是在len(num)-1的它(以及其背后的一个完整停止,这就是您的示例中

所示

for index, x in enumerate(num):
    if index != len(num)-1: #not the last number
        print("{}, ".format(x), end = "");
    else: #the last number
        print("and {}.".format(x), end = "");

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#enumerate

This 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:

for index, x in enumerate(num):
    if index != len(num)-1: #not the last number
        print("{}, ".format(x), end = "");
    else: #the last number
        print("and {}.".format(x), end = "");

This yields the output:

1, 2, 3, and 4.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文