Q5 Format a string of names like 'Bart, Lisa & Maggie'.

1.问题描述

2.代码

3.总结


一、问题描述:
Description:

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

二、代码:

** My solution **(我的方法是真的chun,o)

def namelist(names):
    onlyName = []
    for item in names:
        onlyName.append(item.get('name'))
    
    if len(onlyName) == 0 :
        return ""
    elif len(onlyName) == 1:
        return onlyName[0]
    elif len(onlyName) == 2:
        return ' & '.join(onlyName)
    else:
        partOne = onlyName[0:len(onlyName)-2]
        partTwo = onlyName[len(onlyName)-2 : len(onlyName)]
        p1 = ', '.join(partOne)
        p2 = ' & '.join(partTwo)
        p = [p1, p2]
        return ', '.join(p)

** Other Solutions **

  • 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 ''
  • Clever
def namelist(names):
  return ", ".join([name["name"] for name in names])[::-1].replace(",", "& ",1)[::-1]

你可能感兴趣的:(Q5 Format a string of names like 'Bart, Lisa & Maggie'.)