Home > Backend Development > Python Tutorial > How to Convert String Elements in a Nested List to Integers in Python?

How to Convert String Elements in a Nested List to Integers in Python?

Barbara Streisand
Release: 2024-11-24 20:55:11
Original
233 people have browsed it

How to Convert String Elements in a Nested List to Integers in Python?

Converting List Elements to Integers with int()

To convert all string elements within a list of lists into integers, one can utilize Python's built-in int() function. This function accepts a string representing a number and returns the corresponding integer value.

For instance, to convert "1" to an integer, one can use:

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

Given a list of lists containing strings, such as:

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

the goal is to convert all elements to integers, resulting in the following output:

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

To achieve this conversion, one can utilize a list comprehension in Python 3 or a map() function in Python 2. In Python 3, the following code snippet does the conversion:

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

In Python 2, the conversion can be done using:

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

The above is the detailed content of How to Convert String Elements in a Nested List to Integers in Python?. 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