您如何优雅地将包含未知数量元素的列表转换为用户界面的叙述性文本表示形式?
例如:
>>> elements = ['fire', 'water', 'wind', 'earth']
>>> narrative_list(elements)
'fire, water, wind and earth'
最佳答案
def narrative_list(elements):
last_clause = " and ".join(elements[-2:])
return ", ".join(elements[:-2] + [last_clause])
然后像这样运行
>>> narrative_list([])
''
>>> narrative_list(["a"])
'a'
>>> narrative_list(["a", "b"])
'a and b'
>>> narrative_list(["a", "b", "c"])
'a, b and c'
关于python - 创建列表的叙述字符串的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23316673/