Python练习题答案: 格式词成句【难度:2级】--景越Python编程实例训练营,1000道上机题等你来挑战

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/aumtopsale/article/details/102752566

格式词成句【难度:2级】:

答案1:

def format_words(words):
    return ', '.join(word for word in words if word)[::-1].replace(',', 'dna ', 1)[::-1] if words else ''

答案2:

def format_words(words):
    words = [w for w in words if w] if words else ''
    if not words:
        return ''
    return '{seq} and {last}'.format(seq=', '.join(words[:-1]), last=words[-1]) if len(words) !=1 else '{0}'.format(words[0])

答案3:

def format_words(words):
    # reject falsey words
    if not words: return ""
    
    # ignoring empty strings
    words = [word for word in words if word]
    
    number_of_words = len(words)
    if number_of_words <= 2:
        # corner cases:
        # 1) list with empty strings
        # 2) list with one non-empty string
        # 3) list with two non-empty strings
        joiner = " and " if number_of_words == 2 else ""
        return joiner.join(words)
    
    return ", ".join(words[:-1]) + " and " + words[-1]

答案4:

from itertools import chain

def format_words(words):
    if not words: return ''
    
    filtered = [s for s in words if s]
    nCommas  = len(filtered)-2
    nAnd     = min(1,len(filtered)-1)
    chunks   = [', '] * nCommas + [' and '] * nAnd + ['']
    
    return ''.join(chain(*zip(filtered, chunks)))

答案5:

def format_words(words):
    if words == None: return ''
    w = [x for x in words if x != '']
    s = ''
    if not w: return s
    if len(w) == 1: return str(w[0])
    for i in range(len(w)-2):
        if i == '':
            break
        s += "{}, ".format(w[i])
    s += "{} and {}".format(w[-2], w[-1])
    return s​

答案6:

def format_words(words):
    if not words or words == ['']:
        return ''
    words = [i for i in words if i != '']
    if len(words) == 1:
        return words[0]
    return ', '.join(words[:-1]) + ' and ' + words[-1]

答案7:

def format_words(w):
  if w in [[],[''], None]:
    return ''
  else:
    w = [i for i in w if i != '']
    return w[0] if len(w) == 1 else ', '.join(w[:-1]) + ' and %s' % w[-1]

答案8:

def format_words(words):
    return " and ".join(", ".join(filter(bool, words or [])).rsplit(", ", 1))

答案9:

def format_words(words):
  return ' and '.join(', '.join(filter(bool, words or [])).rsplit(', ', 1))

答案10:

def format_words(words):
    if words is not None:
        while not all(words): words.remove('')
        return ' and '.join(words).replace(' and', ',', len(words)-2)
    return ''

答案11:

def format_words(words):
    if words is None:
        return ""
    filtered = list(filter(lambda x: x != None and len(x) > 0, words))
    if len(filtered) == 0:
        return ""
    
    return filtered[0] if len(filtered) == 1 else ', '.join(filtered[:-1]) + ' and ' + filtered[-1]



Python基础训练营景越Python基础训练营QQ群

在这里插入图片描述
欢迎各位同学加群讨论,一起学习,共同成长!

猜你喜欢

转载自blog.csdn.net/aumtopsale/article/details/102752566