How the map works

I have a line of code that:

D = {'h' : 'hh' , 'e' : 'ee'}
str = 'hello'
data = ''.join(map(lambda x:D.get(x,x),str))
print data

it gives a way out → hheello

I am trying to understand how the map function works. Does the card accept each character string and compare it with a dictionary key and return the corresponding key value?

How is this done for each character? There are no iterations. Is there a good example to better understand this?

+3
source share
5 answers

Separate str elements are required. The following is readable code for the same implementation:

D = { 'h' : 'hh' , 'e' : 'ee'}
str = 'hello'
returns = []  # create list for storing return value from function
def myLambda(x): # function does lambda 
    return D.get(x,x)

for x in str: #map==> pass iterable 
    returns.append(myLambda(x)) #for each element get equivalent string from dictionary and append to list

print ''.join(returns) #join for showing result
0
source

There is no loop, because it maprequires "iteration" (that is, an object on which you can iterate), and the loop itself.

mapif it is absent initially, it can be implemented as:

def map(f, it):
    return [f(x) for x in it]

or, even more explicitly, as:

def map(f, it):
    result = []
    for x in it:
        result.append(f(x))
    return result

Python , .

map(ord, "hello")

[104, 101, 108, 108, 111]

.

+2

. .

map(lambda x: 10*x, [1,2,3,4])

[10, 20, 30, 40]
+2

, :

MAP (f, L) L '

Input:

  • L - n [e1, e2,..., en]
  • f -

  • L - L f : [f (e1), f (e2),..., f (en)]

, , e :

x str; return D.get(x, x)

, ( ) 'hh' 'ee' 'h' 'e', , .

+1

str , map() (lambda ) . [ map()][2] , , .

, :

str2 = "123"
print map(int, str2)
>>> [1, 2, 3]

str2 int:

int("1") -> 1
int("2") -> 2
int("3") -> 3

list:

[1, 2, 3]

Note. Do not use Python inline names as variable names. Do not use stras a variable name, because you are hiding your inline implementation. Use str1, my_stro, s... instead

0
source

All Articles