格式化哈希数组

'''
给定:一个包含名字哈希的数组
返回:格式化为名称之间用逗号分隔,最后两个名称之间应该用与号分隔。
namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])
# returns 'Bart, Lisa & Maggie'
'''
#解法1
def namelist(names):
    names=[name['name'] for name in names]
    name_nums=len(names)
    if name_nums==0:
        return ''
    elif name_nums==2:
        return '&'.join(names)
    elif name_nums>=3:
        return ','.join(names[0:-2])+','+'&'.join(names[-2:])
    else:
        return ''.join(names)

print(namelist([]))

#解法2:直接把最后一个,替换成&
def namelist2(names):
  # return ", ".join([name["name"] for name in names])[::-1].replace(",", "& ",1)[::-1]
    return ", ".join([name["name"] for name in names])[::-1].replace(",", "& ",1)[::-1]

print(namelist2([ {'name': 'Bart'}, {'name': 'Lisa'} ]))

#解法3
def namelist3(names):
    name_list=[name['name'] for name in names]
    return ' & '.join(', '.join(name_list).rsplit(', ',1))

print(namelist3([ {'name': 'Bart'}, {'name': 'Lisa'} ]))

 

posted @ 2020-03-31 14:31  pple  阅读(224)  评论(0编辑  收藏  举报
以终为始,你期待的那天不会太遥远。