码迷,mamicode.com
首页 > 编程语言 > 详细

Python题库

时间:2018-05-08 14:22:12      阅读:753      评论:0      收藏:0      [点我收藏+]

标签:mes   rate   lis   orm   practice   tmp   form   fir   att   

Date:2018-05-08

1、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 ‘‘

Best Practices:

def namelist(names):
    if len(names) > 1:
        return ‘{} & {}‘.format(‘, ‘.join(name[‘name‘] for name in names[:-1]), 
                                names[-1][‘name‘])
    elif names:
        return names[0][‘name‘]
    else:
        return ‘‘

My solutions:

def namelist(names):
    #your code here
    if len(names) > 1:
        first_name = ‘, ‘.join(tmp_name[‘name‘] for tmp_name in names[:-1])
        last_name = names[-1][‘name‘]
        print(first_name)
        print(last_name)
        return first_name + ‘ & ‘ + last_name
    elif names:
        return names[0][‘name‘]
    else:
        return ‘‘

Python题库

标签:mes   rate   lis   orm   practice   tmp   form   fir   att   

原文地址:https://www.cnblogs.com/---wunian/p/9007362.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!