如何在python中获取交替值的数组?

时间:2011-08-22 23:22:56

标签: python numpy

这里的简单问题:

我正在尝试获取一个替换给定长度的值(1,-1,1,-1 .....)的数组。 np.repeat只给我(1,1,1,1,-1,-1,-1,-1)。想法?

7 个答案:

答案 0 :(得分:20)

我喜欢@Benjamin的解决方案。另一种选择是:

import numpy as np
a = np.empty((15,))
a[::2] = 1
a[1::2] = -1

这也允许奇数列表。

编辑:还要注意速度,对于10000个元素的数组

import numpy as np
from timeit import Timer

if __name__ == '__main__':

    setupstr="""
import numpy as np
N = 10000
"""

    method1="""
a = np.empty((N,),int)
a[::2] = 1
a[1::2] = -1
"""

    method2="""
a = np.tile([1,-1],N)
"""

    method3="""
a = np.array([1,-1]*N)   
"""

    method4="""
a = np.array(list(itertools.islice(itertools.cycle((1,-1)), N)))    
"""
    nl = 1000
    t1 = Timer(method1, setupstr).timeit(nl)
    t2 = Timer(method2, setupstr).timeit(nl)
    t3 = Timer(method3, setupstr).timeit(nl)
    t4 = Timer(method4, setupstr).timeit(nl)

    print 'method1', t1
    print 'method2', t2
    print 'method3', t3
    print 'method4', t4

结果时间:

method1 0.0130500793457
method2 0.114426136017
method3 4.30518102646
method4 2.84446692467

如果N = 100,事情开始平衡,但从空的numpy数组开始仍然明显加快(nl更改为10000)

method1 0.05735206604
method2 0.323992013931
method3 0.556654930115
method4 0.46702003479

Numpy数组是特殊的真棒对象,不应该被视为python列表。

答案 1 :(得分:9)

使用resize():

In [38]: np.resize([1,-1], 10) # 10 is the length of result array
Out[38]: array([ 1, -1,  1, -1,  1, -1,  1, -1,  1, -1])

它可以产生奇数长度数组:

In [39]: np.resize([1,-1], 11)
Out[39]: array([ 1, -1,  1, -1,  1, -1,  1, -1,  1, -1,  1])

答案 2 :(得分:7)

使用numpy.tile

import numpy
a = numpy.tile([1,-1], 15)

答案 3 :(得分:4)

使用乘法:

[1,-1] * n

答案 4 :(得分:4)

如果您想要一个内存有效的解决方案,请尝试以下方法:

def alternator(n):
    for i in xrange(n):
        if i % 2 == 0:
            yield 1
        else:
            yield -1

然后你可以像这样迭代答案:

for i in alternator(n):
    # do something with i

答案 5 :(得分:2)

也许你正在寻找itertools.cycle?

list_ = (1,-1,2,-2)  # ,3,-3, ...

for n, item in enumerate(itertools.cycle(list_)):
    if n==30:
        break

    print item

答案 6 :(得分:0)

我会把它们扔出去,因为它们在某些情况下会更有用。

如果你只想在正面和负面之间交替:

[(-1)**i for i in range(n)]

或更一般的解决方案

nums = [1, -1, 2]
[nums[i % len(nums)] for i in range(n)]
相关问题