Python循环中用单个元素替换多个索引的实现方案
Got it, let's work through this problem to get your desired output. Your initial thought about identifying merge ranges is solid, but let's tweak the trigger point to make the logic cleaner. Instead of checking for "B3 Ring Wave:", we can start merging when we hit an element that starts with "Model "—since that's the clear start of each block we need to combine, and we know each block has exactly 4 elements (Model line + 3 subsequent lines).
Here's a straightforward implementation:
Step 1: Use a while loop for index control
We'll use a while loop instead of a regular for loop because we need to skip multiple elements once we process a merge block. This gives us full control over how we increment the index, which is key for avoiding reprocessing lines.
Step 2: Trigger merges at "Model " lines
Whenever we encounter an element starting with "Model ", we combine that element plus the next 3 into a single string separated by newlines. Then we jump the index ahead by 4 to skip those processed lines. For all other elements, we add them to the result list as-is.
Full Code Example
original = ["Some Other Sting","-277/480V RATED:","Model L-N:","B3 Ring Wave: 600","C3 Combined Wave: 1300","6kV-3Ka UL VPR: 1200","Model L-G:","B3 Ring Wave: 875","C3 Combined Wave: 1300","6kV-3Ka UL VPR: 1200","Some other string"] result = [] i = 0 total_items = len(original) while i < total_items: # Start merging when we hit a "Model " line if original[i].startswith("Model "): # Combine current item + next 3 into one with newlines merged_block = '\n'.join(original[i:i+4]) result.append(merged_block) # Skip the next 3 items since we've processed them i += 4 else: # Add non-merge items directly to the result result.append(original[i]) i += 1 # Optional: Print the result to verify for idx, item in enumerate(result): print(f"Element {idx + 1}:") print(item) print("-" * 30)
What the Output Looks Like
The final result list will have 5 elements:
"Some Other Sting""-277/480V RATED:"- The merged L-N block (with newlines between each line)
- The merged L-G block (with newlines between each line)
"Some other string"
Why This Approach Works
- Clear trigger point: Starting merges at the "Model " line directly targets the start of each block we need to combine, eliminating ambiguity about where the merge range begins.
- Controlled index movement: The
whileloop lets us skip 3 elements after merging, so we never reprocess the same lines.
内容的提问来源于stack exchange,提问作者CRapai

