检测交替信号 [英] Detect alternating signs

查看:57
本文介绍了检测交替信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种很好的简短方法来判断python列表(或numpy数组)是否包含带有交替符号的数字?换句话说:

Is there a nice and short way to tell whether a python list (or numpy array) contains numbers with alternating signs? In other words:

is_alternating_signs([1, -1, 1, -1, 1]) == True
is_alternating_signs([-1, 1, -1, 1, -1]) == True
is_alternating_signs([1, -1, 1, -1, -1]) == False

推荐答案

好的,这要归功于SO的相关"功能.我发现了这个问题并采纳了 ianalis 的答案,并采纳了

OK, thanks to SO "related" feature. I found this question and adopted the answer by ianalis and the comment by lazyr

def is_alternating_signs(a):
    return numpy.all(numpy.abs(numpy.diff(numpy.sign(a))) == 2)



print is_alternating_signs([1, -1, 1, -1, 1]) 
print is_alternating_signs([-1, 1, -1, 1, -1]) 
print is_alternating_signs([1, -1, 1, -1, -1]) 

输出为

True
True
False

这篇关于检测交替信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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