Home > Backend Development > Python Tutorial > How to Convert Strings in Nested Tuples to Integers in Python?

How to Convert Strings in Nested Tuples to Integers in Python?

Linda Hamilton
Release: 2024-12-05 20:57:10
Original
506 people have browsed it

How to Convert Strings in Nested Tuples to Integers in Python?

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'))
Copy after login

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]]
Copy after login

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]
Copy after login

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]
Copy after login

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!

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