返回字符串中最长的单词

时间:2018-10-08 20:41:13

标签: python python-3.x

我需要定义一个函数“ len_score”,该函数返回单词的长度。调用len_score函数作为参数的“最佳”函数。

我想要的输出是: print(best(len_score,names),“具有最长的名称。”)

McJagger的名字最长。

我的代码是:

def len_score(name):
    lst=[len(x) for x in name]
    return lst
def best(lst1,lst2):
    final=zip(lst1,lst2)
    return max final

names = ["Ben", "April", "Zaber", "Alexis", "McJagger", "J.J.", "Madonna"]

print(best(len_score, names) == 'McJagger')

但是我遇到错误,不确定如何在列表中设置条件。

2 个答案:

答案 0 :(得分:0)

您快到了:

def len_score(name):
    lst=[len(x) for x in name]
    return lst

def best(lst1,lst2):
    final=zip(lst1,lst2)
    return max(final)

names = ["Ben", "April", "Zaber", "Alexis", "McJagger", "J.J.", "Madonna"]

print(best(len_score(names), names)[1])
print(best(len_score(names), names)[1] == 'McJagger')

工作代码:https://py3.codeskulptor.org/#user302_Lx3nAppYJe_0.py

答案 1 :(得分:0)

我认为您想做的是:

def len_score(name):
    lst = [len(x) for x in name]
    return lst

def best(func, lst):
    func_lst = func(lst) # call the passed in function ON lst
    return lst[func_lst.index(max(func_lst))]

names = ["Ben", "April", "Zaber", "Alexis", "McJagger", "J.J.", "Madonna"]

print(best(len_score, names) == 'McJagger')