Home > Backend Development > Python Tutorial > How Can I Convert a Nested List of Strings to a Nested List of Floats Using List Comprehensions?

How Can I Convert a Nested List of Strings to a Nested List of Floats Using List Comprehensions?

Patricia Arquette
Release: 2024-12-10 19:44:11
Original
1012 people have browsed it

How Can I Convert a Nested List of Strings to a Nested List of Floats Using List Comprehensions?

Converting a Nested List to Float with List Comprehensions

To process a nested list using list comprehensions, you can employ a two-level loop structure.

Given a nested list like:

l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']]
Copy after login

To convert each element in l to a float with a nested list comprehension, you can use the following code:

[[float(y) for y in x] for x in l]
Copy after login

This nested comprehension loops through the outer list x and then the inner list y to convert each element to a float, resulting in a list of lists with floats.

For a flat list, you can use:

[float(y) for x in l for y in x]
Copy after login

In this case, the comprehension loops through the outer list first to avoid creating a nested list.

The above is the detailed content of How Can I Convert a Nested List of Strings to a Nested List of Floats Using List Comprehensions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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