python - Python中的语法列表连接

标签 python list

最pythonic的加入列表的方式是什么,以便每个项目之间有逗号,除了最后一个使用“and”的项目?

["foo"] --> "foo"
["foo","bar"] --> "foo and bar"
["foo","bar","baz"] --> "foo, bar and baz"
["foo","bar","baz","bah"] --> "foo, bar, baz and bah"

最佳答案

这个表达式做到了:

print ", ".join(data[:-2] + [" and ".join(data[-2:])])

如下所示:

>>> data
    ['foo', 'bar', 'baaz', 'bah']
>>> while data:
...     print ", ".join(data[:-2] + [" and ".join(data[-2:])])
...     data.pop()
...
foo, bar, baaz and bah
foo, bar and baaz
foo and bar
foo

关于python - Python中的语法列表连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19838976/

相关文章:

python - 在 Heroku 上找不到与 torch==1.5.0+cpu 匹配的分布

python - 将不同的对象状态添加到列表中

python - 将重复列表转换为具有相同键的组合列表

list - 方案/ Racket : A function which separates a list into two lists of elements that match a certain predicate and those that don't match it

python - 如何衡量覆盖率(在生产系统中)?

python - Django 上下文处理器和具有多个应用程序的 Django 项目

python - 有没有办法以列表格式填充数据框中的缺失值作为上一行列表的最后一个值?

r - 从列表和子列表中提取 xts 对象

linux - 为什么命令 "perf list"在相同版本的 RedHat Linux 上产生不同的输出?

python - 将 Python 模块作为参数传递是一个好习惯吗