Home  >  Article  >  Backend Development  >  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
Barbara StreisandOriginal
2024-11-24 20:55:11223browse

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

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'))

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]]

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]

In Python 2, the conversion can be done using:

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

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!

Statement:
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