2014-04-26 6 views
1

알 수없는 요소가있는 목록을 사용자 인터페이스의 서사 텍스트 표현으로 어떻게 우아하게 변환 하시겠습니까? 예를 들어목록의 서사 스트링을 만드는 우아한 방법

:

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

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

정확히 원하는 것입니까? 쉼표와 끝에 _and_ 단어? –

답변

5
def narrative_list(elements): 
    last_clause = " and ".join(elements[-2:]) 
    return ", ".join(elements[:-2] + [last_clause]) 

처럼 실행되는
1
>>> ', '.join(elements[:-1])+' and '+elements[-1] 
'fire, water, wind and earth' 

편집 :이 두 요소의 목록을 위해 일 것입니다,하지만 당신은 하나의 요소 목록 (또는 빈 목록)

+7

참고 : 특별한 경우가 아닌 매우 짧은 목록 (두 개 미만의 요소)을 원할 수 있습니다. –

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) 
에 대한 특별한 경우를 할 수 있습니다
+0

좋은 해결책이지만 맵이 생성자를 반환하는 python3에서는 작동하지 않습니다. 'map' 대신에'[element에 e를 위해 [str (e)]'를 사용하십시오. – Thomas

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

요소에 쉼표가 있으면 실패합니다. – CoDEmanX

+0

요소 끝에 단어 끝에 쉼표가 포함되어 있고 단어에 공백이 있으면 실패합니다. – alvas

2

파이썬에는 사용자가 원하는대로 할 수있는 기존의 libs가 매우 많이 있습니다. 당신이 인간화를 많이하고 있다면 나는 단지이 신경 것 humanfriendly 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 자 종속성을 제거하므로).

관련 문제