编写获取Top10观看率视频的函数及现有代码问题排查
First, let's break down what's wrong with your current code and walk through a correct, working implementation step by step.
What's Broken in Your Code?
L.items()is invalid: Your inputLis a list of tuples, not a dictionary. Lists don't have anitems()method—this is throwing an AttributeError immediately.- No aggregation for duplicate videos: Your code treats each tuple as a separate entry, but you need to sum up view rates for the same video name first to get accurate totals.
- No return of top 10 names: Your code only prints a sorted list, but the requirement is to return a list of the top 10 video names.
Correct Implementation Steps
Here's a solution that fixes all these issues and meets your requirements:
Step 1: Aggregate Total Views per Video
First, calculate the total view rate for each unique video. We can use a dictionary to track sums:
def ranked_games(L): # Build a dictionary of total views per video view_totals = {} for video, views in L: # Use get() to safely add to existing totals or initialize new entries view_totals[video] = view_totals.get(video, 0) + views
For a cleaner approach, you can use collections.defaultdict (no extra error handling needed):
from collections import defaultdict def ranked_games(L): view_totals = defaultdict(int) for video, views in L: view_totals[video] += views
Step 2: Sort by Total Views (Descending)
Next, sort the aggregated entries from highest to lowest view count. Adding a secondary alphabetical sort ensures consistent results for videos with the same total:
# Sort by views descending, then video name ascending sorted_videos = sorted(view_totals.items(), key=lambda x: (-x[1], x[0]))
Step 3: Extract Top 10 Video Names
Finally, pull the first 10 entries from the sorted list and return just their names:
# Get the top 10 video names top_10 = [video for video, _ in sorted_videos[:10]] return top_10
Full Working Code (No Imports Needed)
def ranked_games(L): # Aggregate total views for each video view_totals = {} for video, views in L: view_totals[video] = view_totals.get(video, 0) + views # Sort videos by total views (descending) and name (ascending) sorted_videos = sorted(view_totals.items(), key=lambda x: (-x[1], x[0])) # Return the top 10 video names return [video for video, _ in sorted_videos[:10]]
Example Test Run
Using your sample input:
L = [('abc',10),('def',15),('ghi',10),('abc', 12),('xyz',100)] print(ranked_games(L)) # Output: ['xyz', 'abc', 'def', 'ghi']
Key Takeaways
- Always match your code to the input type: Lists don't have
items()—save that for dictionaries. - Aggregation is non-negotiable: Duplicate video names need their view counts summed to get meaningful rankings.
- Sort with negative keys for easy descending order: This avoids having to call
reverse()separately.
内容的提问来源于stack exchange,提问作者Rachel

