如何从含元组的列表中提取符合前后值规则的目标元素列表?
Got it, let's fix your loop to get the exact result you're expecting. The key is to track a "collecting" state that triggers when we see a 0 followed by a 1, then collect all subsequent 1s until we hit a 0 (which we also collect) before switching back to waiting for the next trigger.
First, let's handle the input list by filtering out any None values since they shouldn't be included in the result. Then we'll use a state-based loop to collect the right elements:
ov = [(0,), (1,), (0,), (0,), (0,), (0,), (1,), (1,), (1,), (1,), (1,), (0,), (1,), (1,), (1,), (0,), (1,), (1,), (1,), (1,), (1,), (None,)] # Step 1: Filter out None values and extract the single element from each tuple filtered_vals = [item[0] for item in ov if item[0] is not None] result = [] state = "waiting" # Can be "waiting" or "collecting" for i in range(len(filtered_vals)): current_val = filtered_vals[i] if state == "waiting": # Trigger collecting only if current is 0 and the next element is 1 if current_val == 0 and (i + 1) < len(filtered_vals) and filtered_vals[i+1] == 1: state = "collecting" elif state == "collecting": # Add the current value to the result result.append(current_val) # If we hit a 0, switch back to waiting for the next trigger if current_val == 0: state = "waiting" print(result) # Output: [1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1]
How this works:
- Filtering: We first create
filtered_valsto strip out tuples and excludeNone—this simplifies our loop logic since we don't have to handle those edge cases repeatedly. - State Management:
- Waiting State: We're looking for a 0 that's immediately followed by a 1. When we find this pair, we switch to collecting mode.
- Collecting State: We add every element to the result until we hit a 0. Once we hit that 0, we add it to the result and switch back to waiting for the next trigger.
- Edge Handling: If a sequence of 1s ends at the end of the list (instead of a 0), we just keep collecting those 1s until the loop finishes—no extra steps needed.
This logic perfectly matches your expected output, and it's straightforward to follow and modify if you need to adjust the rules later.
内容的提问来源于stack exchange,提问作者mrei
相关产品推荐
相关产品推荐

