46 lines
1.7 KiB
Python
46 lines
1.7 KiB
Python
import json
|
||
from collections import defaultdict
|
||
|
||
# 读取数据
|
||
with open("movies.json", "r", encoding="utf-8") as f:
|
||
data = json.load(f)
|
||
movies = data.get("movies", [])
|
||
|
||
# ① 找出评分最高和最低的电影
|
||
if movies:
|
||
# 按rating排序,处理可能的空值
|
||
sorted_by_rating = sorted(movies, key=lambda x: float(x["rating"]) if x["rating"] else 0)
|
||
lowest = sorted_by_rating[0]
|
||
highest = sorted_by_rating[-1]
|
||
print("评分最低:", lowest["title"], lowest["rating"])
|
||
print("评分最高:", highest["title"], highest["rating"])
|
||
else:
|
||
print("无电影数据")
|
||
|
||
# ② 统计各类型的电影数量(注意genre可能是列表或字符串,这里按常见的逗号分隔处理)
|
||
genre_count = defaultdict(int)
|
||
for movie in movies:
|
||
genres = movie["genre"]
|
||
# 如果genre是字符串,按逗号分割;如果是列表,直接遍历
|
||
if isinstance(genres, str):
|
||
genres = [g.strip() for g in genres.split(",")]
|
||
for g in genres:
|
||
genre_count[g] += 1
|
||
print("\n各类型电影数量:", dict(genre_count))
|
||
|
||
# ③ 统计各导演的电影数量
|
||
director_count = defaultdict(int)
|
||
for movie in movies:
|
||
director = movie["director"]
|
||
director_count[director] += 1
|
||
print("\n各导演电影数量:", dict(director_count))
|
||
|
||
# ④ 统计2020年(含)以后上映的电影数量
|
||
count_2020 = 0
|
||
for movie in movies:
|
||
year = movie["year"]
|
||
if isinstance(year, (int, float)) and year >= 2020:
|
||
count_2020 += 1
|
||
elif isinstance(year, str) and year.isdigit() and int(year) >= 2020:
|
||
count_2020 += 1
|
||
print(f"\n2020年(含)以后上映的电影数量:{count_2020}") |