python的代码不理解,题很简单,只是这种解法不懂

实现一个函数likes :: [String] -> String,该函数必须接受输入数组,
其中包含喜欢某个项目的人的姓名。它必须返回显示文本,如示例所示:
  1. likes([]) # must be "no one likes this"
  2. likes(["Peter"]) # must be "Peter likes this"
  3. likes(["Jacob", "Alex"]) # must be "Jacob and Alex like this"
  4. likes(["Max", "John", "Mark"]) # must be "Max, John and Mark like this"
  5. likes(["Alex", "Jacob", "Mark", "Max"]) # must be "Alex, Jacob and 2 others like this"
def likes(names):
    n = len(names)
    return {
        0: 'no one likes this',
        1: '{} likes this',
        2: '{} and {} like this',
        3: '{}, {} and {} like this',
        4: '{}, {} and {others} others like this'
    }[min(4, n)].format(*names[:3], others=n-2)  #这一行不懂
print(likes(["Alex", "Jacob", "Mark", "Max", "Mark", "Max", "Mark", "Max"]))
输出 Alex, Jacob and 6 others like this
阅读 2.1k
3 个回答

我将代码分解了一下,并加上了注释,应该可以让你看懂。

def likes(names):
    n = len(names)
    temp = {
        0: 'no one likes this',
        1: '{} likes this',
        2: '{} and {} like this',
        3: '{}, {} and {} like this',
        4: '{}, {} and {others} others like this'
    }
    # 找到当前len的对应的返回格式
    text = temp[min(n, 4)]

    # 之后是format方法
    # 假如熟悉str的format方法的话,看下面的注释应该可以理解
    
    # *names[:3]   ==> 取前3位,因为len=3时,要取3位,*用于解包,取多了不会填进去
    #                  而且,["Alex", "Jacob"][:3]这种情况也不会报错,取:["Alex", "Jacob"]
    # others=n - 2 ==> 用于给“{others}”格式化的,没有{others}时,也不会填进去
    
    return text.format(*names[:3], others=n - 2)


print(likes(["Alex", "Jacob", "Mark", "Max", "Mark", "Max", "Mark", "Max"]))

[min(4, n)] 取出對應格式化字符串,人數大於4都用第五個格式化字符串。

.format(*names[:3], others=n-2) 中的 *names[:3] 是將 names 數組切片,取出前三個,然後 * 展開作爲參數。 others=n-2 就是給第五個格式化字符串用的。

def likes(names):
    n = len(names)
    return {
        0: 'no one likes this',
        1: '{} likes this',
        2: '{} and {} like this',
        3: '{}, {} and {} like this',
        4: '{}, {} and {others} others like this'
    }[min(4, n)].format(*names[:3], others=n - 2)  # 这一行不懂
    # min(4, n) 最大值是4
    """
    {
        0: 'no one likes this',
        1: '{} likes this',
        2: '{} and {} like this',
        3: '{}, {} and {} like this',
        4: '{}, {} and {others} others like this'
    }[min(4, n)]
    字典取值,例如:
    {
        0: 'no one likes this',
        1: '{} likes this',
        2: '{} and {} like this',
        3: '{}, {} and {} like this',
        4: '{}, {} and {others} others like this'
    }[4]='{}, {} and {others} others like this'
    """
    # 然后是字符的format,字符串格式化
    # *names[:3] 先看names[:3],取前三位,因为上面最多就用3个,所以这里取三位,format就算传多了也只会使用能用到的
    # 然后*就是转换一下传递方式, 参考:*args,**kwargs函数接值
    # others 是指定值传递,直接付给{others},如果前面没有{others}也不影响
    '{}, {} and {others} others like this'.format(*names[:3], others=n - 2)


print(likes(["Alex", "Jacob", "Mark", "Max", "Mark", "Max", "Mark", "Max"]))

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题