How to Create a Floating-Point Range Sequence in Python?

Barbara Streisand
Release: 2024-10-20 10:54:30
Original
853 people have browsed it

How to Create a Floating-Point Range Sequence in Python?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template