如何在python中获得一个交替值数组?

时间:2022-03-06 12:16:21

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). Thoughts?

我正在尝试得到一个数组,它改变给定长度的值(1,1,1,1,1,1,1,1…)。np。重复,得到(1 1 1 1 1 -1 -1 -1 -1 -1 -1)想法吗?

7 个解决方案

#1


15  

I like @Benjamin's solution. An alternative though is:

我喜欢@Benjamin的解决方案。另一种是:

import numpy as np
a = np.empty((15,))
a[::2] = 1
a[1::2] = -1

This also allows for odd-length lists.

这也允许奇数长度的列表。

EDIT: Also just to note speeds, for a array of 10000 elements

编辑:也只是为了注意速度,对于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

Results in timings of:

结果的时间:

method1 0.0130500793457
method2 0.114426136017
method3 4.30518102646
method4 2.84446692467

If N = 100, things start to even out but starting with the empty numpy arrays is still significantly faster (nl changed to 10000)

如果N = 100,那么事情就开始了,但从空的numpy数组开始,仍然要快得多(nl变为10000)

method1 0.05735206604
method2 0.323992013931
method3 0.556654930115
method4 0.46702003479

Numpy arrays are special awesome objects and should not be treated like python lists.

Numpy数组是特别棒的对象,不应该像python列表那样处理。

#2


7  

use 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])

it can produce odd-length array:

可以产生奇长阵列:

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

#3


6  

Use numpy.tile!

使用numpy.tile !

import numpy
a = numpy.tile([1,-1], 15)

#4


4  

use multiplication:

用乘法:

[1,-1] * n

#5


3  

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

#6


2  

Maybe you're looking for itertools.cycle?

也许您正在寻找itertools.cycle?

list_ = (1,-1,2,-2)  # ,3,-3, ...

for n, item in enumerate(itertools.cycle(list_)):
    if n==30:
        break

    print item

#7


0  

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)]

#1


15  

I like @Benjamin's solution. An alternative though is:

我喜欢@Benjamin的解决方案。另一种是:

import numpy as np
a = np.empty((15,))
a[::2] = 1
a[1::2] = -1

This also allows for odd-length lists.

这也允许奇数长度的列表。

EDIT: Also just to note speeds, for a array of 10000 elements

编辑:也只是为了注意速度,对于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

Results in timings of:

结果的时间:

method1 0.0130500793457
method2 0.114426136017
method3 4.30518102646
method4 2.84446692467

If N = 100, things start to even out but starting with the empty numpy arrays is still significantly faster (nl changed to 10000)

如果N = 100,那么事情就开始了,但从空的numpy数组开始,仍然要快得多(nl变为10000)

method1 0.05735206604
method2 0.323992013931
method3 0.556654930115
method4 0.46702003479

Numpy arrays are special awesome objects and should not be treated like python lists.

Numpy数组是特别棒的对象,不应该像python列表那样处理。

#2


7  

use 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])

it can produce odd-length array:

可以产生奇长阵列:

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

#3


6  

Use numpy.tile!

使用numpy.tile !

import numpy
a = numpy.tile([1,-1], 15)

#4


4  

use multiplication:

用乘法:

[1,-1] * n

#5


3  

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

#6


2  

Maybe you're looking for itertools.cycle?

也许您正在寻找itertools.cycle?

list_ = (1,-1,2,-2)  # ,3,-3, ...

for n, item in enumerate(itertools.cycle(list_)):
    if n==30:
        break

    print item

#7


0  

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)]