Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use index information inside the map function?

Let's assume there is a list a = [1, 3, 5, 6, 8].

I want to apply some transformation on that list and I want to avoid doing it sequentially, so something like map(someTransformationFunction, a) would normally do the trick, but what if the transformation needs to have knowledge of the index of each object?

For example let's say that each element must be multiplied by its position. So the list should be transformed to a = [0, 3, 10, 18, 32].

Is there a way to do that?

like image 325
LetsPlayYahtzee Avatar asked Feb 18 '16 12:02

LetsPlayYahtzee


People also ask

Can we get index in map?

You will be able to get the current iteration's index for the map method through its 2nd parameter. The current element being processed in the array. The index of the current element being processed in the array.

How do you pass an index on a map in Python?

To get access to the index in the map function:Use the enumerate() function to get an object of index/item tuples. Unpack the index and item values in the function you pass to map() . The function will get passed a tuple containing the index and item on each iteration.

How do you pass an index on a map in react?

To use the map() method with index in React: Call the map() method on the array. The function you pass to the map() method gets called with the element and index.

How do I find indexes on a map?

To access the index of the array map() method, use the second argument of the callback function. The array map() method creates the new array populated with the results of calling the provided function on every item in the array.


2 Answers

Use the enumerate() function to add indices:

map(function, enumerate(a)) 

Your function will be passed a tuple, with (index, value). In Python 2, you can specify that Python unpack the tuple for you in the function signature:

map(lambda (i, el): i * el, enumerate(a)) 

Note the (i, el) tuple in the lambda argument specification. You can do the same in a def statement:

def mapfunction((i, el)):     return i * el  map(mapfunction, enumerate(a)) 

To make way for other function signature features such as annotations, tuple unpacking in function arguments has been removed from Python 3.

Demo:

>>> a = [1, 3, 5, 6, 8] >>> def mapfunction((i, el)): ...     return i * el ... >>> map(lambda (i, el): i * el, enumerate(a)) [0, 3, 10, 18, 32] >>> map(mapfunction, enumerate(a)) [0, 3, 10, 18, 32] 
like image 151
Martijn Pieters Avatar answered Oct 14 '22 08:10

Martijn Pieters


You can use enumerate():

a = [1, 3, 5, 6, 8]  answer = map(lambda (idx, value): idx*value, enumerate(a)) print(answer) 

Output

[0, 3, 10, 18, 32] 
like image 24
gtlambert Avatar answered Oct 14 '22 06:10

gtlambert