使用“and"将列表转换为逗号分隔的字符串在最后一项之前 - Python 2.7 [英] Converting a list into comma-separated string with "and" before the last item - Python 2.7
本文介绍了使用“and"将列表转换为逗号分隔的字符串在最后一项之前 - Python 2.7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了这个函数来解析列表:
listy = ['item1','item2','item3','item4','item5','item6']定义昏迷(ABC):对于 abc[0:-1] 中的 i:打印 i+',',打印和"+ abc[-1] + '.'昏迷(列表)#item1、item2、item3、item4、item5和item6.
有没有更简洁的方法来实现这一目标?这应该适用于任何长度的列表.
解决方案
当列表中有 1+ 项时(如果没有,就使用第一个元素):
<预><代码>>>>"{} 和 {}".format(", ".join(listy[:-1]), listy[-1])'item1, item2, item3, item4, item5, and item6'如果您需要一个牛津逗号(甚至不知道它存在!)——只需使用:", and"
istead.
I have created this function to parse the list:
listy = ['item1', 'item2','item3','item4','item5', 'item6']
def coma(abc):
for i in abc[0:-1]:
print i+',',
print "and " + abc[-1] + '.'
coma(listy)
#item1, item2, item3, item4, item5, and item6.
Is there a neater way to achieve this? This should be applicable to lists with any length.
解决方案
When there are 1+ items in the list (if not, just use the first element):
>>> "{} and {}".format(", ".join(listy[:-1]), listy[-1])
'item1, item2, item3, item4, item5, and item6'
Edit: If you need an Oxford comma (didn't know it even existed!) -- just use: ", and"
isntead.
这篇关于使用“and"将列表转换为逗号分隔的字符串在最后一项之前 - Python 2.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文