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

Python3:如何在for循环中增量匹配Scaffold(y)并按y存储对应行

Automatically Group Lines by Scaffold Number in Your Text File

Hey there! Let’s fix this so you don’t have to manually specify each Scaffold(y) number anymore. Instead of creating separate variables for each y value (which gets messy fast), we’ll use a dictionary to group lines by their scaffold number—it’s clean, scalable, and easy to maintain.

Step-by-Step Solution (Python Example)

Here’s a script that will automatically detect all scaffold numbers, group their corresponding lines, and print each group:

import re

# Initialize a dictionary to hold lines grouped by scaffold number
scaffold_groups = {}

# Open and read your text file
with open("xfile", "r") as file:
    for line in file:
        line = line.strip()  # Remove extra whitespace/newlines
        if not line:
            continue  # Skip empty lines
        
        # Use regex to extract the number y from lines starting with Scaffold(y)_1
        match = re.match(r"^Scaffold(\d+)_1", line)
        if match:
            scaffold_num = match.group(1)  # Get the numeric part (y)
            
            # Add the line to the corresponding group in the dictionary
            if scaffold_num not in scaffold_groups:
                scaffold_groups[scaffold_num] = []
            scaffold_groups[scaffold_num].append(line)

# Print each group of lines
for num, lines in scaffold_groups.items():
    print(f"--- Scaffold{num} Lines ---")
    for line in lines:
        print(line)
    print("\n")  # Add a blank line between groups

How This Works:

  • Regex Matching: The pattern ^Scaffold(\d+)_1 targets lines starting with Scaffold, captures the numeric part y, and checks for the _1 suffix. The (\d+) is a capturing group that grabs the number.
  • Dictionary Grouping: We use scaffold_groups to map each scaffold number to a list of its lines. This avoids the hassle of creating dynamic variables (which is generally not recommended in Python).
  • Clean Output: Finally, we loop through the dictionary to print each group with a clear header, so you can easily see all lines for each scaffold number.

Optional: Sort Groups by Scaffold Number

If you want the output to be ordered by the numeric value of y (instead of the order they appeared in the file), modify the final loop to sort the keys:

# Sort the scaffold numbers numerically before printing
for num in sorted(scaffold_groups.keys(), key=int):
    lines = scaffold_groups[num]
    print(f"--- Scaffold{num} Lines ---")
    for line in lines:
        print(line)
    print("\n")

This will ensure you see Scaffold1, Scaffold2, Scaffold3, etc., in order, regardless of how they’re arranged in the input file.

内容的提问来源于stack exchange,提问作者Cormac Tomás Ó Grífín

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:04:21