Python习题(5)
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:
1 namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ]) 2 # returns 'Bart, Lisa & Maggie' 3 4 namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ]) 5 # returns 'Bart & Lisa' 6 7 namelist([ {'name': 'Bart'} ]) 8 # returns 'Bart' 9 10 namelist([]) 11 # returns ''
Solution:
首先分析Given data,namelist是个列表与字典混合的类型,如果读取Bart,用namelist[0]['name']的写法。
判断names是否为[],如果为空则直接返回;如果不为空,再用join和format的方法进行字符串拼接。
1 def namelist(names): 2 if names: 3 return '{} & {}'.format(', '.join(name['name'] for name in names[:-1]), names[-1]['name']) 4 else: 5 return ""