【发布时间】:2014-04-26 21:23:12
【问题描述】:
您如何优雅地将具有未知数量元素的列表转换为用户界面的叙述性文本表示?
例如:
>>> elements = ['fire', 'water', 'wind', 'earth']
>>> narrative_list(elements)
'fire, water, wind and earth'
【问题讨论】:
-
这正是您想要的吗?逗号和末尾的 and 词?
您如何优雅地将具有未知数量元素的列表转换为用户界面的叙述性文本表示?
例如:
>>> 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'
【讨论】:
def narrative_list(elements):
"""
Takes a list of words like: ['fire', 'water', 'wind', 'earth']
and returns in the form: 'fire, water, wind and earth'
"""
narrative = map(str, elements)
if len(narrative) in [0, 1]:
return ''.join(narrative)
narrative.append('%s and %s' % (narrative.pop(), narrative.pop()))
return ', '.join(narrative)
【讨论】:
map,使用[str(e) for e in elements]。
在 python 中有非常(非常)经常存在的库来做你想做的事。查看人性化https://pypi.python.org/pypi/humanfriendly/1.7.1
>>> import humanfriendly
>>> elements = ['fire', 'water', 'wind', 'earth']
>>> humanfriendly.concatenate(elements)
'fire, water, wind and earth'
如果你做了很多人性化,我只会打扰这个。否则我喜欢 Hugh Bothwell 的回答(因为它消除了代码中的第三方依赖)。
【讨论】:
>>> ', '.join(elements[:-1])+' and '+elements[-1]
'fire, water, wind and earth'
编辑:这适用于二元素列表,但您可能需要一元素列表(或空列表)的特殊情况
【讨论】:
>>> elements = ['fire', 'water', 'wind', 'earth']
>>> ", ".join(elements)[::-1].replace(' ,', ' dna ',1)[::-1]
'fire, water, wind and earth'
>>> elements = ['fire']
>>> ", ".join(elements)[::-1].replace(' ,', ' dna ',1)[::-1]
'fire'
>>> elements = ['fire', 'water']
>>> ", ".join(elements)[::-1].replace(' ,', ' dna ',1)[::-1]
'fire and water'
【讨论】: