如何获取movies列表中指定电影的description字符串长度?
问题解决:获取指定电影的描述长度
错误原因
你当前的代码存在两个核心问题:
- 函数
get_movie_description_length期望接收一个电影字典,但你调用时传入的是电影名字符串'The Godfather',执行dictionary_entry['description']时会把字符串当作字典操作,触发TypeError。 - 代码完全没有用到
movies列表,根本无法从列表中定位到对应电影的字典条目。
修正后的代码
假设你的movies列表结构如下(示例):
movies = [ { 'title': 'The Godfather', 'description': 'Spanning the years 1945 to 1955, a chronicle of the fictional Italian-American Corleone crime family. When organized crime family patriarch, Vito Corleone barely survives an attempt on his life, his youngest son, Michael steps in to take care of the would-be killers, launching a campaign of bloody revenge.', 'genre': 'Crime, Drama' }, # 其他电影条目... ]
修改函数,让它能从movies列表中匹配指定标题的电影,并返回描述长度:
def get_movie_description_length(movies_list, target_title): # 遍历列表查找目标电影 for movie in movies_list: if movie['title'] == target_title: return len(movie['description']) # 未找到目标电影时返回None(或根据需求抛出异常/返回0) return None # 调用函数并输出结果 result = get_movie_description_length(movies, 'The Godfather') if result is not None: print(result) # 输出149 else: print("未找到指定电影")
代码说明
- 函数新增两个参数:
movies_list(你的电影列表)和target_title(要查找的电影标题)。 - 通过遍历列表匹配电影标题,找到对应字典后计算
description的字符串长度并返回。 - 增加了未找到电影的处理逻辑,避免程序无提示出错。
内容的提问来源于stack exchange,提问作者James Riley
相关产品推荐
相关产品推荐

