You can either use:
[x / 10.0 for x in range(5, 50, 15)]
or use lambda / map:
map(lambda x: x/10.0, range(5, 50, 15))
Answer from Grzegorz Rożniecki on Stack OverflowYou can either use:
[x / 10.0 for x in range(5, 50, 15)]
or use lambda / map:
map(lambda x: x/10.0, range(5, 50, 15))
def frange(x, y, jump):
while x < y:
yield x
x += jump
---
As the comments mention, this could produce unpredictable results like:
>>> list(frange(0, 100, 0.1))[-1]
99.9999999999986
To get the expected result, you can use one of the other answers in this question, or as @Tadhg mentioned, you can use decimal.Decimal as the jump argument. Make sure to initialize it with a string rather than a float.
>>> import decimal
>>> list(frange(0, 100, decimal.Decimal('0.1')))[-1]
Decimal('99.9')
Or even:
import decimal
def drange(x, y, jump):
while x < y:
yield float(x)
x += decimal.Decimal(jump)
And then:
>>> list(drange(0, 100, '0.1'))[-1]
99.9
[editor's not: if you only use positive jump and integer start and stop (x and y) , this works fine. For a more general solution see here.]
Float contained in range - Ideas - Discussions on Python.org
float numbers with range () function
How to step by floats in a range function?
Fast path for "float in range" checks - Ideas - Discussions on Python.org
Videos
Hi, I have a section of code which takes a score from the user, typecasts it into a float value and saves it under the variable name "score". Then I have a line of code which reads:
while score not in range(0, 101):
However, when I input a float, I get an invalid input error message from python. I think it's because I can't use the range() function with floats. Is there a way around this? If anyone knows how to solve this, then your help would be greatly appreciated. Thank you in advance.
The range function does not handle floats
I am trying to convert something from PHP to Python, but came across a problem since the range function can only step by integers.
I will divide a circle into 16 parts. In PHP I have written:
for ($degrees = 0; $degrees < 360; $degrees += 22.5) {
...I was going to write it like this in Python:
for degrees in range(0, 360, 22.5):
...What is the easiest / nicest way to achieve this?