如何用Python找出字典列表中最长电影标题并输出标题及字符数
解决Python字典列表中最长电影标题的查找问题
原代码的问题分析
- 两个
for循环仅会将最后一个电影的标题赋值给title和film_title变量,无法对所有标题进行比较 max(film_title)是取单个字符串中ASCII码最大的字符(最后一个标题"The Godfather: Part II"里最大的字符是"y"),并非查找最长的字符串- 返回的
len(title)是最后一个电影标题的长度,不是所有标题中最长的那个
修正方案一:使用max函数(简洁高效)
直接利用Python内置的max函数,通过key参数指定以标题长度为比较依据,快速找到最长标题对应的字典:
def get_max_movie_name_length(): # 按标题长度找到最长的电影字典 longest_movie = max(movies, key=lambda x: len(x["title"])) title = longest_movie["title"] return [title, len(title)] # 定义电影字典列表 movies = [{'title': 'The Shawshank Redemption'}, {'title': 'The Godfather'}, {'title': 'The Dark Knight'}, {'title': 'The Godfather: Part II'}] # 调用函数并输出结果 result = get_max_movie_name_length() print(f'"{result[0]}" "{result[1]}"')
修正方案二:遍历比较(适合初学者理解)
通过遍历逐个比较每个标题的长度,实时更新最长标题及其长度:
def get_max_movie_name_length(): max_length = 0 longest_title = "" for movie in movies: current_title = movie["title"] current_length = len(current_title) # 如果当前标题更长,更新记录 if current_length > max_length: max_length = current_length longest_title = current_title return [longest_title, max_length] # 定义电影字典列表 movies = [{'title': 'The Shawshank Redemption'}, {'title': 'The Godfather'}, {'title': 'The Dark Knight'}, {'title': 'The Godfather: Part II'}] # 调用函数并输出结果 result = get_max_movie_name_length() print(f'"{result[0]}" "{result[1]}"')
运行结果
执行上述代码后,会输出期望的结果:
"The Shawshank Redemption" "24"
内容的提问来源于stack exchange,提问作者Marina Roque
相关产品推荐
相关产品推荐

