python - 检测交替迹象

标签 python numpy

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

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“相关”功能。我找到了 this question并通过ianalis的答案和 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

关于python - 检测交替迹象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6451514/

相关文章:

python - 按顺序从 HTML 中提取数据

python - 在 NumPy 中获取 ndarray 的索引和值

python - numpy.where 返回 int 而不是 float

python - 使用 `nbytes` 广播后,numpy 数组中的 `broadcast_to` 值错误

python - 有没有办法从 python 数组中删除相似的(数字)元素

python - 为什么 matlab 中的反向 for 循环更快

python - 与 numpy 的大型稀疏矩阵的余弦相似度

python - 是否有 Eclipse 插件可以构建用于分发的 python 可执行文件?

python - 使用 Pandas 将多个时间序列行合并为一行

python - 使 OrderedDict 中的重复值唯一