用于创建列表的叙述字符串的优雅方式

Tho*_*mas 1 python string nlp

您如何优雅地将具有未知数量元素的列表转换为用户界面的叙述文本表示?

例如:

>>> elements = ['fire', 'water', 'wind', 'earth']

>>> narrative_list(elements)
'fire, water, wind and earth'
Run Code Online (Sandbox Code Playgroud)

Hug*_*ell 5

def narrative_list(elements):
    last_clause = " and ".join(elements[-2:])
    return ", ".join(elements[:-2] + [last_clause])
Run Code Online (Sandbox Code Playgroud)

然后运行像

>>> narrative_list([])
''
>>> narrative_list(["a"])
'a'
>>> narrative_list(["a", "b"])
'a and b'
>>> narrative_list(["a", "b", "c"])
'a, b and c'
Run Code Online (Sandbox Code Playgroud)