简体   繁体   中英

Python loop compare values of a list

I am looking for a way to compare values of a list:

count = 0

list = [120, 134, 155, 145, 160, 190, 200, 185]

So if a value is smaller than previous values the count needs to increase by 1, in the case on top the count should be 2, because 145 is smaller than 155 and 185 also is smaller than 200.

I was thinking something like that

for this in mylist:
    for that in mylist:
        compare(this, that)

Try this:

import numpy as np

def n_decrease(lst):
    return np.sum(np.diff(lst) < 0)

print(n_decrease([120, 134, 155, 145, 160, 190, 200, 185]))

np.diff computes the difference between consecutive values. Then we check whether the difference is negative. Finally, we sum over the indicators of whether the difference is negative, which gives the value we want.

You can use zip and sum :

lst = [120, 134, 155, 145, 160, 190, 200, 185]

output = sum(x > y for x, y in zip(lst, lst[1:]))
print(output) # 2

Or, with python 3.10+, you can use itertools.pairwise :

from itertools import pairwise

lst = [120, 134, 155, 145, 160, 190, 200, 185]

output = sum(x > y for x, y in pairwise(lst))

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