简体   繁体   中英

How to divide each element in list by first element

Lets consider some list:

arr = [2, 4, 6, 8, 10]

I need to divide each element of list by its first element. It can be done with list compehension:

[e / arr[0] for e in arr]

but I have to use some functional programming for this

map :

>>> arr = [2, 4, 6, 8, 10]
>>> list(map(lambda x: x/arr[0],arr))
[1.0, 2.0, 3.0, 4.0, 5.0]

Or as a function:

>>> def f(x):
    return x/arr[0]

>>> list(map(f,arr))
[1.0, 2.0, 3.0, 4.0, 5.0]
>>> 

Or use numpy:

>>> import numpy as np
>>> arr2=np.array(arr)
>>> arr2/arr[0]
array([ 1.,  2.,  3.,  4.,  5.])
>>> 

and if you want list:

>>> import numpy as np
>>> arr2=np.array(arr)
>>> (arr2/arr[0]).tolist()
[1.0, 2.0, 3.0, 4.0, 5.0]
>>> 

You can use the built-in function map in combination with the class list :

arr = [2, 4, 6, 8, 10]
new_arr = list(map(lambda x: x / arr[0], arr))

map() returns an iterator that applies a function to every item of iterable, yielding the results.

list() takes an iterable in order to produce a list.

Use map :

arr = [2, 4, 6, 8, 10]
out = list(map(lambda x: x/arr[0], arr))

And if you don't like the lambda expression, you can use the truediv (or floordiv ) method in operator , but two parameters are required so here I used a little trick.

from operator import truediv
from itertools import starmap
arr = [2, 4, 6, 8, 10]
arr = zip(arr, [arr[0]]*len(arr))
out = list(starmap(truediv, arr))
print(out)

I first build a new iterable according to the question, and then use starmap which can map multiple parameters to a function. truediv in operator has exactly the same functionality as operator / but just make it run in a function way and accept two parameters and return the div result between them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM