简体   繁体   中英

How can I take every Kth number of a list and measure against the prior nth numbers of the same list?

I want to take every 10th number in a list and compare it to the last 9 numbers from the 10th number of the same list and check if any of the last 9 prior numbers fall within +100/-100 range of the 10th number.

So If I have a list with, say 10,000 numbers;

large_list = [4504, 4405, 4302, 4706, 4332, 4656, 3045, 1056, 4556, 4032, 4504, 4405, 4302, 4706, 3342, 3356, 3245, 2356, 4156, 4300, .....]

In this instance, every 10th number is 4032 & 4300 and so I want to check if any of the last 9 numbers from 4032 fall within 3932 & 4132, and then check if any of the last 9 prior numbers from 4300 fall within 4200 and 4400, so on and so forth.

You just need to use the built-in any() function to see if any of the last 10 satisfy the condition.

large_list = [4504, 4405, 4302, 4706, 4332, 
              4656, 3045, 1056, 4556, 4032, 
              4504, 4405, 4302, 4706, 3342, 
              3356, 3245, 2356, 4156, 4300]

within_range = []
step = 10

for i in range(step - 1, len(large_list), step):
    within_range.append(any(large_list[i] - 100 <= large_list[i-j] <= large_list[i] + 100 for j in range(1, step)))

This will go through every 10th element in the list and add True to the within_range list if any of the previous 9 elements were within 100 of it and False otherwise.

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