如何遍历Python坐标二维列表并对应修改y轴数值
Hey Calvin! Sounds like you've already nailed the x-axis grouping part—great job getting that sorted. Now let's get those y-values mapped to the -5 to 5 range as needed. I'll walk you through two common approaches depending on how you want the y-axis distributed:
Option 1: Linear Y-Value Distribution (Smooth Range)
If you want every coordinate's y-value to smoothly span from -5 to 5 across all 100 elements (so the first element has y=-5, last has y=5, and everything in between scales linearly), here's a straightforward way to do it:
# Assume your pre-processed coordinate list is named coords y_min = -5 y_max = 5 total_coords = len(coords) for idx in range(total_coords): # Map the index (0-99) to the y range using linear interpolation mapped_y = y_min + (y_max - y_min) * (idx / (total_coords - 1)) coords[idx][1] = mapped_y
Or if you prefer a more concise list comprehension:
y_min, y_max = -5, 5 total = len(coords) coords = [[x, y_min + (y_max - y_min)*(i/(total-1))] for i, (x, _) in enumerate(coords)]
Option 2: Grouped Y-Values (Per X-Group Fixed Y)
If you want each group of 10 coordinates (sharing the same x-value) to have a fixed y-value that increments from -5 to 5 (e.g., first x-group [-5,y] gets y=-5, next [-4,y] gets y=-4, etc.), use this approach:
coords = [...] # Your existing list with x-values sorted into groups num_groups = 10 # Since 100 elements = 10 groups of 10 y_start = -5 y_end = 5 # Calculate the step between each group's y-value y_step = (y_end - y_start) / (num_groups - 1) if num_groups > 1 else 0 for group_num in range(num_groups): # Define the start/end indices for the current group group_start = group_num * 10 group_end = group_start + 10 # Compute the y-value for this group current_y = y_start + group_num * y_step # Update every coordinate in the group for coord in coords[group_start:group_end]: coord[1] = current_y
Note: If your x-axis actually uses 11 groups (to cover from -5 to 5 inclusive with integer steps), just change num_groups to 11—this will adjust the y-step automatically to span -5 to 5 across 11 groups.
内容的提问来源于stack exchange,提问作者calvin fraser

