简体   繁体   English

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

[英]Elegant way for creating a narrative string of a list

How would you elegantly convert a list with a unknown number of elements into a narrative text representation for user interfaces? 您如何将元素数量未知的列表优雅地转换为用户界面的叙述性文本表示形式?

For example: 例如:

>>> 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])

which then runs like 然后像

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

In python there's very (very) often existing libs to do what you want. 在python中,非常(经常)存在的库可以执行您想要的操作。 Check out humanfriendly https://pypi.python.org/pypi/humanfriendly/1.7.1 查看人类友好的https://pypi.python.org/pypi/humanfriendly/1.7.1

>>> import humanfriendly
>>> elements = ['fire', 'water', 'wind', 'earth']
>>> humanfriendly.concatenate(elements)
'fire, water, wind and earth'

I'd only bother with this if you were doing a lot of humanization. 如果您要进行很多人性化的工作,我只会打扰您。 Otherwise I like Hugh Bothwell's answer (as it eliminates the third-party dependency from your code). 否则,我喜欢Hugh Bothwell的答案(因为它消除了代码中的第三方依赖关系)。

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

Edit: This would work for a two-elements list, but you might want a special case for one-element lists (or empty lists) 编辑:这将适用于两个元素的列表,但是您可能想要一种特殊情况下的一个元素的列表(或空列表)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM