You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用for循环实现计数器?及计算唯一ID的SubmissionStatus耗时

Hey there! Let's tackle your two questions step by step—super straightforward once we break them down.

1. Creating a Counter with a For Loop

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 += 1
    
  • Using 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 the start parameter:

    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 here
    

    enumerate() is almost always preferred because it avoids manual counter management and keeps your code cleaner.

2. Calculating Status Duration per Unique ID & Storing Results in a List of Dictionaries

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 LastModified to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:09:18