I need to create a range
like this in Pyhton:
1 ... 4 ... 7 ... 10 ... 13 ... 16 ...
But I would like to estabilish not the end of range , but the number of elements .
For example:
range_num_of_elements(1, num_of_elements=4, interval=3)
Gives as result:
[1, 4, 7, 10]
How can I do it?
EDIT: this question
Creating a range with fixed number of elements (length)
Doesn't answers my question. I wanna specify start, interval, num , where the question above specifies start, end, num .
You can use a list comprehension :
[start + interval * n for n in range(num_of_elements)]
Where
start = 1
interval = 3
num_of_elements = 4
This will give
[1, 4, 7, 10]
Or you can just compute the appropriate arguments to range
, as Tom Karzes suggested in the comments:
range(start, start + interval * num_of_elements, interval)
you could define your range just like this:
def my_range(start, num_elements, step):
return range(start, start+step*num_elements, step)
list(my_range(1, 4, 3))
# [1, 4, 7, 10]
this would have all the nice features of range
; eg:
7 in my_range(1, 4, 3) # True
8 in my_range(1, 4, 3) # False
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.