如何在python中获取一组交替值? [英] How can I get an array of alternating values in python?

查看:65
本文介绍了如何在python中获取一组交替值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一个简单的问题:

Simple question here:

我正在尝试获取一个数组,该数组可以针对给定长度交替更改值 (1, -1, 1, -1.....).np.repeat 只给我 (1, 1, 1, 1,-1, -1,-1, -1).想法?

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?

推荐答案

我喜欢 @Benjamin 的解决方案.不过,另一种选择是:

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

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

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

This also allows for odd-length lists.

也只是注意速度,对于 10000 个元素的数组

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

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

结果时间为:

method1 0.0130500793457
method2 0.114426136017
method3 4.30518102646
method4 2.84446692467

如果 N = 100,事情开始趋于平衡,但从空的 numpy 数组开始仍然明显更快(nl 更改为 10000)

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

method1 0.05735206604
method2 0.323992013931
method3 0.556654930115
method4 0.46702003479

Numpy 数组是特别棒的对象,不应被视为 Python 列表.

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

这篇关于如何在python中获取一组交替值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆