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!