如何用Numpy的arange函数生成20个连续的2的倍数数组?
arange Hey there! Let's walk through this together since you're new to Python and NumPy—no worries, this is a straightforward task once you map it to how np.arange works.
First, let's recap what you already know: np.arange(start, stop, step) generates numbers starting at start, incrementing by step, and stopping before stop.
To get 20 consecutive multiples of 2, here's how to approach it with custom variables (which makes your code flexible and easy to adjust later):
Step 1: Import NumPy
First, you need to import the NumPy library (we usually alias it as np for brevity):
import numpy as np
Step 2: Define your custom variables
Let's break down the values we need into variables so you can tweak them easily if needed:
start: The first multiple of 2 (that's2)step: The difference between consecutive multiples (also2, since we're counting by 2s)num_elements: How many multiples we want (20)stop: Calculate this asstart + step * num_elements—sincearangeexcludes the stop value, this ensures we get exactly 20 elements.
Here's the code for these variables:
start = 2 step = 2 num_elements = 20 stop = start + step * num_elements # This equals 2 + 2*20 = 42
Step 3: Create the array with arange
Now plug these variables into np.arange:
multiples_of_two = np.arange(start, stop, step)
Step 4: Check the result
If you print the array, you'll see 20 consecutive multiples of 2, from 2 up to 40:
print(multiples_of_two) # Output: [ 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40]
Why this works:
Since np.arange(2, 42, 2) starts at 2, adds 2 each time, and stops before 42, it gives us exactly 20 elements (2, 4, ..., 40). Using variables means if you later want, say, 30 multiples of 5, you just change start=5, step=5, num_elements=30—no need to recalculate the stop value manually!
内容的提问来源于stack exchange,提问作者mortis20

