创建一个重复元素的数组,增加0.1个间隔

时间:2015-03-14 18:00:52

标签: python arrays python-2.7 numpy scipy

我想让我的代码做的是创建一个元素数组: [13.8,13.9,14。,...]增加0.1,但每个元素应重复17次,然后再进入下一个数字。以下是我的代码。

from numpy import*
from pylab import*
def f(elem):
return repeat((elem + 0.1),17)
print f(13.8)

def lst(init):
   yield init
   while True:
       next = f(init)
       yield next
       init = next

for i in lst(13.8):
    print i
    if i > 20:
        break

代码输出仅显示重复17次的数组13.9,但随后显示错误:

Traceback (most recent call last):
  File "repeatelementsarray.py", line 19
    if i > 20:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

程序似乎试图创建多个数字数组,我只想要一个数组。此外,由于lst是一个生成器,它不应该给出一个数组,所以使用fromiter?

2 个答案:

答案 0 :(得分:4)

您可以使用np.arange的组合来获得线性增加的序列,并使用np.repeat重复每个元素:

import numpy as np

elems = np.arange(0, 1, 0.1)
reps = np.repeat(elems, 3)

print(reps)
# [ 0.   0.   0.   0.1  0.1  0.1  0.2  0.2  0.2  0.3  0.3  0.3  0.4  0.4  0.4
#   0.5  0.5  0.5  0.6  0.6  0.6  0.7  0.7  0.7  0.8  0.8  0.8  0.9  0.9  0.9]

答案 1 :(得分:0)

基于xrange,您可以生成如下函数:

def repeated_range(start, stop, step=0.1, repeat=5):
    r = start
    while r < stop:
        for i in xrange(repeat):
            yield r
        r += step

这会产生你想要的东西。