Python:如何用一系列数字填充数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37473697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:26:10  来源:igfitidea点击:

Python: How do I fill an array with a range of numbers?

pythonarraysnumpyfill

提问by hpnk85

So I have an array of 100 elements:

所以我有一个包含 100 个元素的数组:

a = np.empty(100)

How do I fill it with a range of numbers? I want something like this:

我如何用一系列数字填充它?我想要这样的东西:

b = a.fill(np.arange(1, 4, 0.25))

So I want it to keep filling awith that values of that range on and on until it reaches the size of it

所以我希望它不断填充a该范围的值,直到达到它的大小

Thanks

谢谢

回答by unutbu

np.putplaces values from binto aat the target indices, ind. If vis shorter than ind, its values are repeated as necessary:

np.put将来自binto 的值放置a在目标索引处ind。如果v短于ind,则根据需要重复其值:

import numpy as np

a = np.empty(100)
b = np.arange(1, 4, 0.25)
ind = np.arange(len(a))
np.put(a, ind, b)
print(a)

yields

产量

[ 1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75]

回答by Ravi Sankar Raju

updating solution to fit description

更新解决方案以适应描述

a = np.empty(100)
filler = np.arange(1,4,0.25)
index = np.arange(a.size)
np.put(a,index,filler)