基于前序元素条件处理列表:Event A关联首个后续Event B数据提取
Solution to Track First Event B for Each Event A
Got it, let's walk through how to implement this logic correctly. The key is to parse the input into discrete events, then for each Event A, find the first Event B that occurs after the previous Event A (or the start of the file) and before the current Event A.
Complete Code Implementation
# Read the file content (you mentioned you already have this part, but included for completeness) with open('events.txt', 'r') as f: tokens = f.read().split() # Group tokens into individual events (each starts with "Event") events = [] current_event = [] for token in tokens: if token == 'Event' and current_event: events.append(current_event) current_event = [] current_event.append(token) if current_event: events.append(current_event) # Process events to build the output output_tokens = [] last_a_index = -1 # Tracks the index of the last encountered Event A for idx, event in enumerate(events): # Add the original event to the output output_tokens.extend(event) if event[1] == 'A': # Look for the first Event B between the last A and current A first_b = None # Check all events from after the last A up to just before current A for j in range(last_a_index + 1, idx): if events[j][1] == 'B': first_b = events[j] break # Append the relevant data or N/A if first_b: output_tokens.extend([first_b[2], first_b[3]]) else: output_tokens.extend(['N/A', 'N/A']) # Update the last A index to current position last_a_index = idx # Generate the final output string final_output = ' '.join(output_tokens) print(final_output)
How It Works
- Parsing Events: We split the input into tokens, then group them into individual events (each starting with "Event"). This makes it easy to iterate through each distinct event without mixing up parts of different events.
- Tracking Previous A: We keep track of the index of the last
Event Awe processed. For each newEvent A, we look in the range from right after the last A to just before the current A. - Finding First B: In that range, we pick the first
Event Bwe encounter. If no B exists in that interval, we useN/A N/Aas the fallback. - Building Output: We add each original event to the output, then append the B data (or N/A) immediately after each
Event Ato match your expected format.
Test with Your Sample Input
For your input string:Event B 0 40 Event B 0 75 Event B 1 30 Event A Event B 1 50 Event B 1 70 Event A Event A Event B 2 40
The code will produce exactly your expected output:Event B 0 40 Event B 0 75 Event B 1 30 Event A 0 40 Event B 1 50 Event B 1 70 Event A 1 50 Event A N/A N/A Event B 2 40
内容的提问来源于stack exchange,提问作者arsenal88
相关产品推荐
相关产品推荐

