Using map function in python
If you have the following code, how exactly is it following the documentation: map(function, iterable,...)
?
x = sorted(map(int, dat[0].split()))
Is i开发者_如何学Gont
a function and if so, why isn't it expressed as such?
int
is a constructor so it's callable so you can use it with map
In your case dat[0]
is as string, and split()
generates a list of strings, by splitting the input string at whitespaces.
Eg
"1 11".split()
returns
["1", "11"]
The map
function has two input arguments:
The first argument is something which can be called (in Python you say it is a callable), eg a function.
int
is not realy a function but such a thing (Python slang: it is an object). Egint("3")
return3
. Soint
when applied to a string tries to convert this string to an integer, and gives the integer value back.The second argument is something you can iterate over, in your case it is a list.
If you then call the map
function, the first argument is applied to all elements from the second argument.
So
map(int, ["1", "11"])
returns
[1, 11]
If you combine what I explained you understand that
map(int, "1 11".split())
returns
[1, 11]
When you ask "why isn't it expressed as such" I suppose you mean, why doesn't it have brackets like a function? The answer is that if you put the brackets in then you get what the function does instead of the function itself. Compare what happens when you enter int()
versus int
.
Think of it like this
def map( function, iterable ):
return ( function(x) for x in iterable )
In x = sorted(map(int, dat[0].split()))
the function, int
, is being named, not evaluated. This code provides a function object to the map
function. The map
function will evaluate the given function.
The syntax of map in the simplest form is:
map(func, sequence)
It will apply the function "func" on each element of the sequence and return the sequence. Just in case you don't know, int() is a function.
>>> int(2.34)
2
>>> int("2")
2
>>> a = ["1", "101", "111"]
>>> map(int, a)
[1, 101, 111]
Now, I will give you my implementation of map().
>>> for index in range(len(a)):
... a[index] = int(a[index])
...
>>> a
[1, 101, 111]
If you have understood the concept, let's take a step further. We converted the strings to int using base 10 (which is the default base of int() ). What if you want to convert it using base 2?
>>> a = ["1", "101", "111"]
>>> for index in range(len(a)):
... a[index] = int(a[index], 2) # We have an additional parameter to int()
...
>>> a
[1, 5, 7]
To get the same result using map(), we will use a lambda function
>>> a = ["1", "101", "111"]
>>> map(lambda x: int(x, 2), a)
[1, 5, 7]
精彩评论