Floating-Point Range Equivalent in Python
Python's range() function doesn't natively support generating sequences of floating-point numbers. This can be a limitation when working with decimal values.
Consider the following example:
<code class="python">>>> range(0.5, 5, 1.5) [0, 1, 2, 3, 4]</code>
As you can see, the resulting sequence excludes the actual starting point of 0.5.
To overcome this, you can create a floating-point range using one of the following methods:
Using List Comprehension
<code class="python">[x / 10.0 for x in range(5, 50, 15)]</code>
This initializes a list with values ranging from 0.5 to 4.5 in increments of 0.5.
Using Lambda and Map
<code class="python">map(lambda x: x / 10.0, range(5, 50, 15))</code>
This creates a map object that applies the lambda function x / 10.0 to each value in the range, resulting in a similar sequence as the list comprehension.
The above is the detailed content of How to Create a Floating-Point Range Sequence in Python?. For more information, please follow other related articles on the PHP Chinese website!