You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 00:17:14