如何用for循环实现计数器?及计算唯一ID的SubmissionStatus耗时
Hey there! Let's tackle your two questions step by step—super straightforward once we break them down.
There are two common, clean ways to do this in Python, depending on your needs:
Manual counter variable (great if you need fine-grained control):
Initialize a variable outside the loop, then increment it on each iteration:counter = 0 items = ["apple", "banana", "cherry"] for item in items: print(f"Processing item #{counter}: {item}") # Do your work with the item here counter += 1Using
enumerate()(the Pythonic approach, less boilerplate):
This built-in function gives you both the counter (index) and the item directly. You can even set a starting value with thestartparameter:items = ["apple", "banana", "cherry"] # Start counting at 1 instead of 0 (default is 0) for counter, item in enumerate(items, start=1): print(f"Processing item #{counter}: {item}") # Do your work with the item hereenumerate()is almost always preferred because it avoids manual counter management and keeps your code cleaner.
Let's walk through this with a concrete example. First, I'll assume your data is structured as a list of dictionaries (each with ID, SubmissionStatus, and LastModified as a datetime object—critical for time calculations).
Step-by-Step Implementation
First, we'll group records by ID, sort each group by timestamp, then track state transitions to calculate durations:
from datetime import datetime from collections import defaultdict # Replace this with your actual dataset sample_data = [ {"ID": "101", "SubmissionStatus": "Pending OSPA", "LastModified": datetime(2024, 5, 1, 10, 0)}, {"ID": "101", "SubmissionStatus": "Pending OSPA", "LastModified": datetime(2024, 5, 1, 11, 0)}, {"ID": "101", "SubmissionStatus": "Pending Department", "LastModified": datetime(2024, 5, 2, 9, 0)}, {"ID": "101", "SubmissionStatus": "Approved", "LastModified": datetime(2024, 5, 3, 14, 0)}, {"ID": "102", "SubmissionStatus": "Pending OSPA", "LastModified": datetime(2024, 5, 1, 15, 0)}, {"ID": "102", "SubmissionStatus": "Pending Department", "LastModified": datetime(2024, 5, 2, 10, 0)}, ] # 1. Group all records by their unique ID id_record_groups = defaultdict(list) for record in sample_data: id_record_groups[record["ID"]].append(record) # 2. Calculate durations for each ID and build the result list final_results = [] for unique_id, records in id_record_groups.items(): # Sort records by LastModified to ensure we follow state transitions in order sorted_records = sorted(records, key=lambda x: x["LastModified"]) # Initialize a dict to store results for this ID id_result = {"ID": unique_id} current_status = None current_status_first_timestamp = None for idx, record in enumerate(sorted_records): status = record["SubmissionStatus"] timestamp = record["LastModified"] if current_status is None: # Set up the first status we encounter current_status = status current_status_first_timestamp = timestamp else: if status != current_status: # Calculate duration per your requirement: earliest timestamp of current status minus next status timestamp # Note: This will give a negative timedelta (since next status is later). Swap the order for positive duration! duration = current_status_first_timestamp - timestamp # Store duration as a readable string (or use total_seconds() for numeric value) id_result[f"{current_status}_duration"] = str(duration) # Update tracking variables for the next status current_status = status current_status_first_timestamp = timestamp # Add this ID's results to the final list final_results.append(id_result) # Print the output to verify for result in final_results: print(result)
Key Notes:
- Sorting is critical: We must sort each ID's records by
LastModifiedto ensure we capture state transitions in the correct order. - Duration calculation: Your requirement asks for the earliest timestamp of the current status minus the next status's timestamp. This will produce a negative value (since time moves forward). If you want a positive duration (time spent in the status), swap the order to
timestamp - current_status_first_timestamp. - Flexible storage: The result is a list of dictionaries where each dict corresponds to one unique ID, with keys for each status duration.
内容的提问来源于stack exchange,提问作者ds920

