How can I get an array of alternating values in python?

后端 未结 7 1878
臣服心动
臣服心动 2020-12-30 01:06

Simple question here:

I\'m trying to get an array that alternates values (1, -1, 1, -1.....) for a given length. np.repeat just gives me (1, 1, 1, 1,-1, -1,-1, -1

相关标签:
7条回答
  • 2020-12-30 01:51

    I'll just throw these out there because they could be more useful in some circumstances.

    If you just want to alternate between positive and negative:

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

    or for a more general solution

    nums = [1, -1, 2]
    [nums[i % len(nums)] for i in range(n)]
    
    0 讨论(0)
提交回复
热议问题