How do I apply int to every string using map and lambda in python?
An answer to this question on Stack Overflow.
Question
I want to avoid doing ugly int to each element in a list.
dictionary[l[0]] = [(int(l[1])+ int(l[2])+ int(l[3]))/3] #avg score of 3 grades
sub1 += int(l[1])
sub2 += int(l[2])
sub3 += int(l[3])
The list l has 4 elements, 0 to 3 indexes. I need to apply int starting with the 1st-element, not 0th element.
I'm trying to write something like:
map lambda x: int(x) for i in l[1:]
Do I need lambda here, since map can already do the job?
Answer
map calls a function on each element of a list. Since int is a function you can use
map(int, lst)
directly.
Lambda functions just give you more flexibility, say if you wanted to do:
map(lambda x: 5*int(x), lst)
A more Pythonic way to do the above would be to use list comprehensions
[int(x) for x in lst]
[5*int(x) for x in lst]
In Python3 map returns a generator. If you wish to have a list, you'd want to do:
list(map(int, lst))