Skip to main content
 首页 » 编程设计

python之创建列表的叙述字符串的优雅方式

2025年05月04日12zfyouxi

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

例如:

>>> 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'