19
votes

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] 
4

4 Answers

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

3
votes
>>> T1 = ['13', '17', '18', '21', '32']
>>> print [int(x) for x in T1]
[13, 17, 18, 21, 32]

You don't need map inside your list comprehension. Map creates another list so you end up with a list of list.

Caveat: This will work if the strings are granted to be numbers otherwise it will raise exception.

1
votes

You can do it like this

>>>T1 = ['13', '17', '18', '21', '32']
>>>list(map(int,T1))
1
votes

1.First,map function is map(func,iterable) 2.see this example:

T1=['13','17','18','21','32']
T3=[map(int, x) for x in T1]
print T3
[[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]]

when choose x out,such as '13',is a sequence,so map(int,'13') return [1,3],so the iterable in map(func,iterable) is string.

3.see this example:

T1 = ['13', '17', '18', '21', '32']
>>>list(map(int,T1))

the iterable object in map function is list.so 'int' works on '13' as 13