本文介绍了Python中的语法列表联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
除了列表中最后一个使用"and"的逗号之外,每个列表之间用逗号隔开的最Python方式是什么?
What's the most pythonic way of joining a list so that there are commas between each item, except for the last which uses "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中的语法列表联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!