Python string.join ( list ) 最后一个带有“and"的条目 [英] Python string.join ( list ) last entry with "and"
问题描述
连接句子部分列表的优雅方式是什么,结果是a, b, and c",其中 list
是 [ 'a', 'b', 'c' ]
?简单地指定 ', '.join()
只实现a, b, c".
What is an elegant way to join a list of sentence parts so that the result is "a, b, and c" where the list
is [ 'a', 'b', 'c' ]
? Specifying simply ', '.join()
achieves only "a, b, c".
(此外,我确实对此进行了一些搜索,但显然我没有尝试写短语,因为除了自己枚举列表之外,我还没有想出任何东西.)
( Also, I did do a few searches on this but obviously I'm not trying the write phrases because I haven't come up with anything besides enumerating the list myself. )
推荐答案
L = ['a','b','c']
if len(L)>2:
print ', '.join(L[:-1]) + ", and " + str(L[-1])
elif len(L)==2:
print ' and '.join(L)
elif len(L)==1:
print L[0]
适用于 0、1、2 和 3+ 的长度.
Works for lengths 0, 1, 2, and 3+.
我包含长度为 2 的原因是为了避免使用逗号:a 和 b
.
The reason I included the length 2 case is to avoid commas: a and b
.
如果列表长度为 1,那么它只输出 a
.
If the list is length 1, then it just outputs a
.
如果列表为空,则不输出任何内容.
If the list is empty, nothing is outputted.
这篇关于Python string.join ( list ) 最后一个带有“and"的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!