gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:55:35 24 4
gpt4 key购买 nike

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

例如:

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com