Anwendungen in der Praxis
Nachdem Sie verschiedene Techniken zum Finden der Top-N-Elemente in einer Python-Liste gelernt haben, wollen wir uns einige Anwendungen in der Praxis ansehen. In diesem Schritt erstellen Sie ein umfassenderes Skript, das diese Konzepte auf praktische Szenarien anwendet.
Erstellen Sie eine neue Datei mit dem Namen practical_applications.py
im Projektverzeichnis und fügen Sie den folgenden Code hinzu:
## Real-world applications of finding top N elements
import heapq
from datetime import datetime
print("PRACTICAL APPLICATIONS OF FINDING TOP N ELEMENTS IN PYTHON LISTS\n")
## Application 1: E-commerce - Analyzing Product Sales
print("APPLICATION 1: E-COMMERCE - ANALYZING PRODUCT SALES")
print("==================================================")
## Sample product sales data (product_id, product_name, units_sold, price)
product_sales = [
(101, "Smartphone X", 1250, 899.99),
(102, "Wireless Earbuds", 2100, 129.99),
(103, "Laptop Pro", 890, 1299.99),
(104, "Smart Watch", 1450, 249.99),
(105, "Tablet Mini", 1050, 399.99),
(106, "Bluetooth Speaker", 1750, 79.99),
(107, "Gaming Console", 780, 499.99),
(108, "Digital Camera", 550, 349.99),
(109, "Power Bank", 1900, 49.99),
(110, "Fitness Tracker", 1350, 129.99)
]
## Find top 3 products by units sold
top_sold_products = heapq.nlargest(3, product_sales, key=lambda x: x[2])
print("\nTop 3 Best-Selling Products (by units sold):")
for product in top_sold_products:
print(f" {product[1]}: {product[2]} units sold at ${product[3]}")
## Find top 3 products by revenue (units_sold * price)
top_revenue_products = heapq.nlargest(3, product_sales, key=lambda x: x[2] * x[3])
print("\nTop 3 Products by Revenue:")
for product in top_revenue_products:
revenue = product[2] * product[3]
print(f" {product[1]}: ${revenue:,.2f} revenue ({product[2]} units at ${product[3]})")
## Application 2: Data Analysis - Temperature Monitoring
print("\n\nAPPLICATION 2: DATA ANALYSIS - TEMPERATURE MONITORING")
print("====================================================")
## Sample temperature data (date, city, temperature)
temperature_data = [
("2023-06-15", "New York", 32.5),
("2023-06-15", "Los Angeles", 28.3),
("2023-06-15", "Chicago", 30.1),
("2023-06-15", "Houston", 35.7),
("2023-06-15", "Phoenix", 40.2),
("2023-06-15", "Miami", 33.8),
("2023-06-15", "Denver", 29.6),
("2023-06-15", "Seattle", 22.4),
("2023-06-15", "Boston", 27.9),
("2023-06-15", "Atlanta", 31.5)
]
## Find cities with highest temperatures
hottest_cities = heapq.nlargest(3, temperature_data, key=lambda x: x[2])
print("\nTop 3 Hottest Cities:")
for city_data in hottest_cities:
print(f" {city_data[1]}: {city_data[2]}°C")
## Find cities with lowest temperatures
coldest_cities = heapq.nsmallest(3, temperature_data, key=lambda x: x[2])
print("\nTop 3 Coldest Cities:")
for city_data in coldest_cities:
print(f" {city_data[1]}: {city_data[2]}°C")
## Application 3: Social Media - User Engagement
print("\n\nAPPLICATION 3: SOCIAL MEDIA - USER ENGAGEMENT")
print("=============================================")
## Sample social media post data (post_id, title, likes, comments, shares, timestamp)
posts = [
(1001, "Breaking News: Major Announcement", 3500, 420, 1200, datetime(2023, 6, 10, 12, 30)),
(1002, "Product Review: Latest Gadget", 2200, 380, 900, datetime(2023, 6, 11, 15, 45)),
(1003, "Tutorial: Python Programming", 1800, 650, 750, datetime(2023, 6, 12, 9, 15)),
(1004, "Travel Tips for Summer Vacation", 2700, 320, 1100, datetime(2023, 6, 13, 18, 20)),
(1005, "Recipe: Delicious Desserts", 3100, 450, 1500, datetime(2023, 6, 14, 11, 10)),
(1006, "Interview with Celebrity", 4200, 580, 2200, datetime(2023, 6, 15, 14, 25)),
(1007, "Health and Fitness Guide", 1500, 280, 600, datetime(2023, 6, 16, 8, 40)),
(1008, "Movie Review: Latest Blockbuster", 2900, 410, 950, datetime(2023, 6, 17, 20, 30)),
(1009, "Tech News: Industry Updates", 2000, 300, 800, datetime(2023, 6, 18, 13, 15)),
(1010, "DIY Home Improvement Projects", 1700, 520, 700, datetime(2023, 6, 19, 16, 50))
]
## Define a function to calculate engagement score (weighted sum of likes, comments, shares)
def engagement_score(post):
return post[2] + (post[3] * 2) + (post[4] * 3) ## likes + (comments * 2) + (shares * 3)
## Find top 3 posts by engagement score
top_engaging_posts = heapq.nlargest(3, posts, key=engagement_score)
print("\nTop 3 Most Engaging Posts:")
for post in top_engaging_posts:
score = engagement_score(post)
print(f" Post ID: {post[0]}")
print(f" Title: {post[1]}")
print(f" Engagement Score: {score}")
print(f" (Likes: {post[2]}, Comments: {post[3]}, Shares: {post[4]})")
print(f" Posted on: {post[5].strftime('%Y-%m-%d %H:%M')}")
print()
## Find top 3 posts by likes
top_liked_posts = heapq.nlargest(3, posts, key=lambda x: x[2])
print("Top 3 Most Liked Posts:")
for post in top_liked_posts:
print(f" {post[1]}: {post[2]} likes")
## Find top 3 posts by comments
top_commented_posts = heapq.nlargest(3, posts, key=lambda x: x[3])
print("\nTop 3 Most Commented Posts:")
for post in top_commented_posts:
print(f" {post[1]}: {post[3]} comments")
Führen Sie das Skript aus, um diese praktischen Anwendungen zu sehen:
python3 practical_applications.py
Sie sollten eine detaillierte Ausgabe sehen, die zeigt, wie das Finden der Top-N-Elemente in realen Szenarien angewendet werden kann:
PRACTICAL APPLICATIONS OF FINDING TOP N ELEMENTS IN PYTHON LISTS
APPLICATION 1: E-COMMERCE - ANALYZING PRODUCT SALES
==================================================
Top 3 Best-Selling Products (by units sold):
Wireless Earbuds: 2100 units sold at $129.99
Power Bank: 1900 units sold at $49.99
Bluetooth Speaker: 1750 units sold at $79.99
Top 3 Products by Revenue:
Smartphone X: $1,124,987.50 revenue (1250 units at $899.99)
Laptop Pro: $1,156,991.10 revenue (890 units at $1299.99)
Wireless Earbuds: $272,979.00 revenue (2100 units at $129.99)
APPLICATION 2: DATA ANALYSIS - TEMPERATURE MONITORING
====================================================
Top 3 Hottest Cities:
Phoenix: 40.2°C
Houston: 35.7°C
Miami: 33.8°C
Top 3 Coldest Cities:
Seattle: 22.4°C
Boston: 27.9°C
Los Angeles: 28.3°C
APPLICATION 3: SOCIAL MEDIA - USER ENGAGEMENT
=============================================
Top 3 Most Engaging Posts:
Post ID: 1006
Title: Interview with Celebrity
Engagement Score: 11560
(Likes: 4200, Comments: 580, Shares: 2200)
Posted on: 2023-06-15 14:25
Post ID: 1005
Title: Recipe: Delicious Desserts
Engagement Score: 8450
(Likes: 3100, Comments: 450, Shares: 1500)
Posted on: 2023-06-14 11:10
Post ID: 1001
Title: Breaking News: Major Announcement
Engagement Score: 8060
(Likes: 3500, Comments: 420, Shares: 1200)
Posted on: 2023-06-10 12:30
Top 3 Most Liked Posts:
Interview with Celebrity: 4200 likes
Breaking News: Major Announcement: 3500 likes
Recipe: Delicious Desserts: 3100 likes
Top 3 Most Commented Posts:
Tutorial: Python Programming: 650 comments
Interview with Celebrity: 580 comments
DIY Home Improvement Projects: 520 comments
Diese Beispiele zeigen, wie die von Ihnen erlernten Techniken auf reale Szenarien wie E-Commerce-Verkaufsanalysen, Wetterdatenanalysen und Social-Media-Engagement-Metriken angewendet werden können. In jedem Fall ist die Fähigkeit, die Top-N-Elemente effizient zu finden, entscheidend, um wertvolle Erkenntnisse aus Daten zu gewinnen.