简体   繁体   English

Python numpy - 用升序填充 numpy 数组

[英]Python numpy - fill numpy array with ascending values

I am trying to initialize a numpy array or a list with ascending values.我正在尝试初始化numpy array或具有升序值的list The number of values is n .值的数量是n

eg: If n = 10例如:如果n = 10

[0,2,4,6,8,10,12,14,16,18]

If n = 2如果n = 2

[0,2]

I am aware that I could use a for like this:我知道我可以像这样使用for

result = []
for x in range(n):
   result.append(x*2)

But when n gets larger this would take a while so I was looking for a faster way.但是当n变大时,这需要一段时间,所以我正在寻找一种更快的方法。

There is numpy.arange which supports a step parameter:numpy.arange支持step参数:

result = np.arange(0, 2*n, 2)

Alternatively, for a list you can use range 's step parameter:或者,对于列表,您可以使用range的 step 参数:

result = list(range(0, 2*n, 2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM