首页 > 代码库 > [codewars 1] Format a string of names like 'Bart, Lisa & Maggie'.
[codewars 1] Format a string of names like 'Bart, Lisa & Maggie'.
任务目标:
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'.
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。