如何在Python中获取交替值数组?
这里有个简单的问题:
我想要一个数组,里面的值交替出现(1, -1, 1, -1……),长度是我指定的。可是用np.repeat这个方法得到的结果是(1, 1, 1, 1, -1, -1, -1, -1)。有没有什么好的想法?
7 个回答
9
使用 numpy.tile
吧!
import numpy
a = numpy.tile([1,-1], 15)
17
使用 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])
30
我喜欢@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列表那样对待。