Home >Backend Development >Python Tutorial >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'))
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]]
The Solution
The int() function transforms a string representing a number into an integer value. For instance:
> int("1") + 1 2
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]
Or use map() directly in Python 2:
T2 = [map(int, x) for x in T1]
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!