Converting Strings to Integers in a Python List
How can you transform a list of strings that represent integers, such as ['1', '2', '3'], into a corresponding list of integers, such as [1, 2, 3]?
To accomplish this conversion, Python offers a straightforward solution:
Given the list xs = ['1', '2', '3']:
Utilize the map function to apply the int function to each element of xs, creating a new list where each string is replaced by its integer value. The resulting object from map is an iterable; you can call the list function on this iterable to transform it into a formal list.
list(map(int, xs))
This function will output:
[1, 2, 3]
In Python 2, the list function wasn't necessary because map returned a list directly:
map(int, xs)
The above is the detailed content of How to Convert a Python List of Strings to a List of Integers?. For more information, please follow other related articles on the PHP Chinese website!