Python3:如何在for循环中增量匹配Scaffold(y)并按y存储对应行
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+)_1targets lines starting withScaffold, captures the numeric party, and checks for the_1suffix. The(\d+)is a capturing group that grabs the number. - Dictionary Grouping: We use
scaffold_groupsto 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

