Python题库

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 ''

猜你喜欢

转载自www.cnblogs.com/---wunian/p/9007362.html