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

Python循环中用单个元素替换多个索引的实现方案

Solution to Merge Consecutive Model Rows into Single Elements in 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:

  1. "Some Other Sting"
  2. "-277/480V RATED:"
  3. The merged L-N block (with newlines between each line)
  4. The merged L-G block (with newlines between each line)
  5. "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 while loop lets us skip 3 elements after merging, so we never reprocess the same lines.

内容的提问来源于stack exchange,提问作者CRapai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 16:57:43