是否有一种简便快捷的方法来判断 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/