Home > Backend Development > Python Tutorial > How to Convert Nested Lists of Strings to Nested Lists of Integers in Python?

How to Convert Nested Lists of Strings to Nested Lists of Integers in Python?

Patricia Arquette
Release: 2024-12-02 02:59:12
Original
962 people have browsed it

How to Convert Nested Lists of Strings to Nested Lists of Integers in Python?

Converting Strings to Integers in Nested Lists

In Python, it can be necessary to convert nested lists containing strings into lists of integers. This goal requires understanding the built-in int() function and applying it to list elements.

The Challenge

Given a tuple of tuples with string elements:

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))
Copy after login

The task is to convert the string elements to integers and store them in a new list of lists:

T2 = [[13, 17, 18, 21, 32],
      [7, 11, 13, 14, 28],
      [1, 5, 6, 8, 15, 16]]
Copy after login

The Solution

The int() function transforms a string representing a number into an integer value. For instance:

> int("1") + 1
2
Copy after login

Knowing the structure of T1 (lists at a single level), you can utilize map() in Python 3:

T2 = [list(map(int, x)) for x in T1]
Copy after login

Or use map() directly in Python 2:

T2 = [map(int, x) for x in T1]
Copy after login

The above is the detailed content of How to Convert Nested Lists of Strings to Nested Lists of Integers in Python?. For more information, please follow other related articles on the PHP Chinese website!

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