Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to integer using map()

Tags:

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]  
like image 508
Rajeev Avatar asked Apr 13 '12 17:04

Rajeev


People also ask

How do you convert a map to an integer in Python?

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.

Can map be used on string?

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.

What is map function in Python?

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.


1 Answers

>>> 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.

like image 50
jamylak Avatar answered Oct 12 '22 23:10

jamylak