例如:
def get_longest_name(a_list):
count = 0
for i in a_list:
if len(i) > count:
count = len(i)
word = i
return word
def main():
print("1.", get_longest_name(["Candide", "Jessie", "Kath", "Amity",
"Raeanne"]))
print("2.", get_longest_name(["Josephine", "Jessie", "Penelope", "Jin",
"Rosamunda", "Annabelle"]))
print("3.", get_longest_name(["Alan", "Jess", "Amity", "Rosalie",
"Raeanne"]))
print("4. ", "***", get_longest_name(["Jo", "Jai", "Jen", "Jing", "Joey",
"Jess"]), "***", sep = "")
print("5. ", "***", get_longest_name([]), "***", sep = "")
print("6.", "***" + get_longest_name([""]) + "***")
main()
输出如:
1. Candide
2. Josephine
3. Rosalie
4. ***Jing***
我已经得到三个正确的输出(三个最长的名字)。该函数应该返回列表中具有最多字符(最长的单词)的单词但是只考虑具有六个或更多字符的单词。如果列表中的两个或多个单词具有与最长单词相同的字符数,则该函数应返回列表开头具有最多字符的第一个单词。如果参数列表为空或者列表中没有包含六个或更多字符的单词,则该函数应返回空字符串。所以输出就像:
1. Candide
2. Josephine
3. Rosalie
4. ******
5. ******
6. ******
答案 0 :(得分:4)
您可以将max()
与key=len
:
def get_longest_name(a_list, min_length=6):
return max((name for name in a_list if len(name) >= min_length), key=len, default='')
生成器表达式处理a_list
以仅包含长度为> = 6的名称。
答案 1 :(得分:1)
@mhawke解决方案的替代方案:
def get_longest_name(a_list, min_length=6):
longest = max(a_list, key=len) if a_list else ''
return longest if longest and len(longest) >= min_length else ''