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

如何用Numpy的arange函数生成20个连续的2的倍数数组?

Creating a NumPy Array of 20 Consecutive Multiples of 2 with 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's 2)
  • step: The difference between consecutive multiples (also 2, since we're counting by 2s)
  • num_elements: How many multiples we want (20)
  • stop: Calculate this as start + step * num_elements—since arange excludes 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:43:45