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

时间:2014-04-26 21:23:12

标签: python string nlp

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

例如:

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

>>> narrative_list(elements)
'fire, water, wind and earth'

5 个答案:

答案 0 :(得分:5)

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'

答案 1 :(得分:2)

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)

答案 2 :(得分:2)

在python中,非常(非常)经常存在的lib可以做你想要的。查看人性化的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的答案(因为它消除了代码中的第三方依赖)。

答案 3 :(得分:1)

>>> ', '.join(elements[:-1])+' and '+elements[-1]
'fire, water, wind and earth'

编辑:这适用于双元素列表,但您可能需要一个单元素列表(或空列表)的特殊情况

答案 4 :(得分:1)

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