Python-计算符号变化 [英] Python - counting sign changes
问题描述
我有一个从左到右阅读的数字列表.每当我在阅读要计数的序列时遇到符号变化时.
I have a list of numbers I am reading left to right. Anytime I encounter a sign change when reading the sequence I want to count it.
X = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1]
X = [-, +, +, -, +, -, +, +, -, -,-,+]
因此,此列表中有8个符号更改.
So, in this list there are 8 sign changes.
如果项目[0]
(在这种情况下为-3)为负,则视为符号更改.同样,列表中的任何0都被视为[-]
.
When Item [0]
(in this case -3) is negative it is considered a sign change. Also, any 0 in the list is considered [-]
.
任何帮助将不胜感激.
Any help would be greatly appreciated.
推荐答案
您可以使用 itertools.groupby
计算正数和非正数的组:
You can use itertools.groupby
to count the groups of positive and non-positive numbers:
>>> x = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1]
>>> import itertools
>>> len(list(itertools.groupby(x, lambda x: x > 0)))
结果:
8
在您的问题中,您要求:
In your question you state that you want:
- 计算更改,而不是分组
- 如果第一个元素不是正数,则计算额外的变化.
您可以通过直接测试第一个元素并调整结果来做到这一点:
You can do this either by testing the first element directly and adjusting the result:
>>> len(list(itertools.groupby(x, lambda x: x > 0))) - (x[0] > 0)
或在进行分组之前在输入之前加上一个正数,然后从结果中减去1:
or by prepending a positive number to the input before doing the grouping then subtracting 1 from the result:
>>> len(list(itertools.groupby(itertools.chain([1], x), lambda x: x > 0))) - 1
当心您的输入列表是否可以为空-前一种解决方案将引发异常.
Watch out if your input list could by empty - the former solution will raise an exception.
这篇关于Python-计算符号变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!