Converting Strings in Nested Lists to Integers
Given a tuple of tuples containing strings, such as:
T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16'))
The task is to convert each string element into an integer and store the result in a new list of lists, as shown below:
T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
Solution:
Python provides the int() function to convert a string into an integer. To convert all the strings in a list of lists, you can use a list comprehension:
T2 = [list(map(int, x)) for x in T1]
This comprehension iterates over each inner list in T1 and uses the map() function to convert each string element into an integer. The result is a new list of lists.
Note:
For Python 2 compatibility, you can replace map with list inside the comprehension:
T2 = [list(int(y) for y in x) for x in T1]
The above is the detailed content of How to Convert Strings in Nested Tuples to Integers in Python?. For more information, please follow other related articles on the PHP Chinese website!