简体   繁体   中英

Count number of times the numbers are increasing in Python list

I have this list of numbers: {199, 200, 208, 210, 200, 207, 240}.

  1. I want to determine how the numbers are increasing or decreasing in the list. For instance, after 199 I have 200, that is a difference of 1. But after 200, I have 208 which is a difference of 8. How do I determine this measure of increase/decrease for the entire list in Python?

  2. Secondly, I want to count how many times the numbers are increasing. As the list consist of increasing and decreasing numbers both, I just want to count how many times it is increasing.

Thank you.

You can use zip() to pair up elements with their successors and process them in list comprehensions:

numbers = [199, 200, 208, 210, 200, 207, 240]

increments = [b-a for a,b in zip(numbers,numbers[1:]) if b>a]
decrements = [b-a for a,b in zip(numbers,numbers[1:]) if a>b]

print(increments)      # [1, 8, 2, 7, 33]
print(decrements)      # [-10]
print(len(increments)) # 5

Addressing your issue #1, you can calculate the Spearmans correlation with x values increasing. It has value in the range [-1, 1], if value is positive then y increases as x increases, if value is negative then y decreases as x increases, if value is zero then there is no correlation. If value is high like close to 1 or -1 then it strongly suggests that both data are highly correlated. So even if you don't plot the data, you can already tell if the trend is positive or negative or no relation by knowing the Spearmans value.

Code

from scipy.stats import spearmanr
import matplotlib.pyplot as plt


y = [199, 200, 208, 210, 200, 207, 240]
x = range(len(y))

# calculate spearman's correlation
corr, _ = spearmanr(x, y)
print('Spearmans correlation: %.3f' % corr)

plt.plot(x, y, '--*')
plt.savefig('corr.png')
plt.show()

Output

Spearmans correlation: 0.667

在此处输入图像描述

References

diff = [l[i+1] - l[i] for i in range(len(l) - 1)]
num_inc = sum([l[i+1] > l[i] for i in range(len(l) - 1)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM