任务目标:
Given: an array containing hashes of names
Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
Example:
namelist([ {‘name‘: ‘Bart‘}, {‘name‘: ‘Lisa‘}, {‘name‘: ‘Maggie‘} ])
# returns ‘Bart, Lisa & Maggie‘
namelist([ {‘name‘: ‘Bart‘}, {‘name‘: ‘Lisa‘} ])
# returns ‘Bart & Lisa‘
namelist([ {‘name‘: ‘Bart‘} ])
# returns ‘Bart‘
namelist([])
# returns ‘‘
解决方案:
def namelist(names): str = "" if len(names) == 0: pass elif len(names) == 1: str = str + (names[0][‘name‘]) else: for each in names[0:-2]: str = str + (each[‘name‘]) + (‘, ‘) str = str + (names[-2][‘name‘]) + (‘ & ‘) + (names[-1][‘name‘]) return str
codewars上的解决方案:from ezetter
def namelist(names): if len(names)==0: return ‘‘ if len(names)==1: return names[0][‘name‘] return ‘, ‘.join([n[‘name‘] for n in names[:-1]]) + ‘ & ‘ + names[-1][‘name‘]
参考资料
http://www.linuxidc.com/Linux/2011-09/42950.htm
[codewars 1] Format a string of names like 'Bart, Lisa & Maggie'.
时间: 2024-08-10 07:57:09