简体   繁体   中英

Count up/down within a specific number range using Python

I'm sure this must've been asked before, but I couldn't find anything like that, sorry.

Let's say I have a list of numbers [1..24] :

numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

I want to make a function that accepts two integers: mynum which is a number in the list and modifier . It will then find mynum in the list and then cycle through the list modifier number of positions (right if positive, left if negative). If it reaches the end of the list, it will loop to the other side.

What I want now is to basically shift the number mynum based on the input, within the list.

Example:

shift_function(2, 1)   # returns 3
shift_function(23, 3)  # returns 2
shift_function(4, -8)  # returns 20
shift_function(15, 51) # returns 18

How can I cycle through the ends of a list like this?

I thought of using the time module to get a time with mynum as current hour and then add/subtract modifier hours to it. This will work with my [1..24] range but I'm looking for a more general solution to this what seems to be a simple problem.

Edit: To clearify further, I simply want to count through a list of numbers. If the end is reached, start over from the beginning, same backwards.

Edit2: I don't know how much more clear I have to be. Imagine you have big numbers on your desk: 3,4,5,6,7. And then you start at the 5 and take modifier steps to the right, let's say 3 steps. So you count: "six, seven, three", starting over from the beginning again. If modifier is negative, you count backwards. Eg with -4 you count: "four, three, seven, six".

I can't see how this is so hard to get. Seems like a very simple and common problem to me.

Looks like this function does what you want:

def shift_function(n, shift):
   return numbers[(numbers.index(n) + shift) % len(numbers)]

You can do this with numpy , using np.roll . Just be aware that the negative is actually inverse relative to what you want, so you can use -modifier instead:

import numpy as np

numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

mynum = 4
modifier = -8

>>> np.roll(numbers,-modifier)[numbers.index(mynum)]
20

mynum = 15
modifier = 51

>>> np.roll(numbers,-modifier)[numbers.index(mynum)]
18

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