如何快速生成0-90步长0.1的列表?替代MATLAB式批量定义方法
Great question! I totally get wanting to skip the tedious for-loop assignments when creating your 0-to-90 list with a 0.1 step—Python has a couple of clean, MATLAB-esque ways to do this in one line:
1. Use numpy.arange() (most similar to MATLAB's syntax)
This function works almost exactly like MATLAB's start:step:end notation. Just pass your start value, step size, and a slightly adjusted end value (since arange uses a half-open interval):
import numpy as np L1 = np.arange(0, 90.1, 0.1)
We use 90.1 instead of 90 here because arange includes the start but excludes the end value. This ensures the last element in your list is exactly 90, not 89.9.
2. Use numpy.linspace() (focus on exact endpoint count)
If you'd rather specify the total number of points instead of the step size, linspace is perfect. Since 0 to 90 with 0.1 steps gives exactly 901 points (from 0 to 90 inclusive), you can write:
import numpy as np L1 = np.linspace(0, 90, 901)
This method avoids worrying about interval edge cases—you'll always get the exact start and end values you want, evenly spaced.
Quick note for your plotting workflow
Once you have L1, you can compute your second list (L2) efficiently, even if your calculation can't be vectorized:
# Example: Replace this with your actual per-point calculation def calculate_y(x): # Your custom logic here return x * 0.5 + np.sin(np.radians(x)) # List comprehension (cleaner than a for loop with append) L2 = [calculate_y(x) for x in L1] # Then plot using your stat plot tool with L1 as x-axis, L2 as y-axis
No more manual loop assignments—these methods will save you time and make your code more readable!
内容的提问来源于stack exchange,提问作者user74671

