这里简单的问题:
我正在尝试获取一个数组,该数组交替给定长度的值(1,-1,1,-1 .....).np.repeat只给我(1,1,1,1,-1,-1,-1,-1).思考?
Jos*_*del 23
我喜欢@Benjamin的解决方案.另一种选择是:
import numpy as np
a = np.empty((15,))
a[::2] = 1
a[1::2] = -1
Run Code Online (Sandbox Code Playgroud)
这也允许奇数列表.
编辑:也只是注意速度,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
Run Code Online (Sandbox Code Playgroud)
结果时间:
method1 0.0130500793457
method2 0.114426136017
method3 4.30518102646
method4 2.84446692467
Run Code Online (Sandbox Code Playgroud)
如果N = 100,事情开始平衡,但从空的numpy数组开始仍然明显更快(nl改为10000)
method1 0.05735206604
method2 0.323992013931
method3 0.556654930115
method4 0.46702003479
Run Code Online (Sandbox Code Playgroud)
Numpy数组是特殊的令人敬畏的对象,不应该被视为python列表.
HYR*_*YRY 10
使用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])
Run Code Online (Sandbox Code Playgroud)
它可以产生奇数长度的数组:
In [39]: np.resize([1,-1], 11)
Out[39]: array([ 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1])
Run Code Online (Sandbox Code Playgroud)
用numpy.tile!
import numpy
a = numpy.tile([1,-1], 15)
Run Code Online (Sandbox Code Playgroud)
小智 5
如果你想要一个内存高效的解决方案,试试这个:
def alternator(n):
for i in xrange(n):
if i % 2 == 0:
yield 1
else:
yield -1
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样迭代答案:
for i in alternator(n):
# do something with i
Run Code Online (Sandbox Code Playgroud)