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

后端 未结 7 1916
臣服心动
臣服心动 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:43

    If you want a memory efficient solution, try this:

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

    Then you can iterate over the answers like so:

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

提交回复
热议问题