简体   繁体   English

利用 for 循环和 numpy.tile 创建交替值数组,即 (1, -3, 5, -7, 9, -11...)

[英]Utilising for loop and numpy.tile to create an array of alternating values i.e. (1, -3, 5, -7, 9, -11...)

Is it possible to combine for loop and numpy.tile to create an alternating incremental array?是否可以结合for loopnumpy.tile来创建交替增量数组?

numpy.tile(A, reps) constructs an array by repeating A the number of times given by reps . numpy.tile(A, reps)通过将 A 重复 reps 给定的次数来构造一个数组 Since you want to alternate values, I don't think it is possible (or at least, preferable) to use this function to achieve your goal.由于您想要交替值,我认为使用此 function 来实现您的目标是不可能的(或者至少,更可取)。

How about using only a for loop (list comprehension)?仅使用for循环(列表理解)如何?

output = [i * (1 if i % 4 == 1 else -1) for i in range(1, 25, 2)]

use resize() :使用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])

for odd length:对于奇数长度:

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

Out[39]: array([ 1, -1,  1, -1,  1, -1,  1, -1,  1, -1,  1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM