In the following i am trying to convert the first list to a integer list using the map function how can i achieve this
T1 = ['13', '17', '18', '21', '32'] print T1 T3=[map(int, x) for x in T1] print T3 [[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]] Expected is: T3=[13,17,18,21,32]
To convert a list of strings to a list of integers, you can “map to int” by calling map(int, lst) on the int built-in function object as first and the lst object as second argument. The result is a map object that you can convert back to a list using the list() function.
Use map() function with string Or the map() function is meant only to work with lists? You can turn a string into a list with something like a_list = list(a_string) . Yes. map always returns a map object.
Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a single transformation function to all the iterable elements. The iterable and function are passed as arguments to the map in Python.
>>> T1 = ['13', '17', '18', '21', '32'] >>> T3 = list(map(int, T1)) >>> T3 [13, 17, 18, 21, 32]
This does the same thing as:
>>> T3 = [int(x) for x in T1] >>> T3 [13, 17, 18, 21, 32]
so what you are doing is
>>> T3 = [[int(letter) for letter in x] for x in T1] >>> T3 [[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]]
Hope that clears up the confusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With