def get_top_10_directors(): directors_info = {} # 查询满足条件的电影信息 films = FilmInfo.query.all() for film in films: directors_str = film.director.strip("[]") # 去除方括号和单引号 directors = directors_str.split(",") directors = [director.strip("'") for director in directors]#统计导演参与的电影数量 for director in directors: if director in directors_info: directors_info[director]['total_films'] += 1 else: directors_info[director] = {'total_films': 1,'best_films': 0, 'worst_films': 0,'average_films': 0} #判断电影评分并更新好片、烂片和一般片数量 if film.rate is not None : if film.rate >= 8.5: for director in directors: if director in directors_info: directors_info[director]['best_films '] += 1 elif film.rate < 6: for director in directors: if director in directors_info: directors_info[director]['worst_films'] += 1 else: for director in directors: if director in directors_info: directors_info[director][' average_films'] += 1 #过滤掉执导电影数量少于5部的导演 directors_info = {director: info for director,info in directors_info.items() if info['total_films'] > 5} #计算好片占比并排序 top_10_directors = sorted(directors_info.items(),key=lambda x: x[1]['best_films']/x[1]['total_films'], reverse=True)[:10] return top_10_directors 请优化并改正这段代码
时间: 2024-02-25 22:56:51 浏览: 54
这段代码可以进行如下优化和改正:
1. 对于查询所有电影信息的部分,可以使用更加高效的查询方式,比如分页查询或者使用查询过滤条件等;
2. 在统计导演参与的电影数量时,可以使用字典的 get 方法来获取导演信息,避免重复代码;
3. 在更新好片、烂片和一般片数量时,应该只更新对应导演的信息,而不是更新所有导演的信息;
4. 在判断电影评分时,应该使用 elif 而不是多个 if,避免多次判断;
5. 在更新好片、烂片和一般片数量时,应该使用 += 而不是 =,避免覆盖之前的信息;
6. 在计算好片占比并排序时,应该先判断导演参与的电影数量是否为 0,避免出现除以零的情况。
改进后的代码如下:
```python
def get_top_10_directors():
directors_info = {}
# 分页查询满足条件的电影信息
films = FilmInfo.query.paginate(1, 1000).items
for film in films:
directors_str = film.director.strip("[]")
# 去除方括号和单引号
directors = [director.strip("'") for director in directors_str.split(",")]
# 统计导演参与的电影数量
for director in directors:
info = directors_info.get(director, {'total_films': 0, 'best_films': 0, 'worst_films': 0, 'average_films': 0})
info['total_films'] += 1
directors_info[director] = info
# 判断电影评分并更新好片、烂片和一般片数量
if film.rate is not None:
for director in directors:
info = directors_info.get(director, {'total_films': 0, 'best_films': 0, 'worst_films': 0, 'average_films': 0})
if film.rate >= 8.5:
info['best_films'] += 1
elif film.rate < 6:
info['worst_films'] += 1
else:
info['average_films'] += 1
directors_info[director] = info
# 过滤掉执导电影数量少于5部的导演
directors_info = {director: info for director, info in directors_info.items() if info['total_films'] > 5}
# 计算好片占比并排序
top_10_directors = sorted(directors_info.items(), key=lambda x: x[1]['best_films'] / x[1]['total_films'] if x[1]['total_films'] > 0 else 0, reverse=True)[:10]
return top_10_directors
```
阅读全文