Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, divide all numbers in a 2d list by 10 and return a 2d list

Tags:

python

I wrote this solution, and coming from Ruby it seems very elegant. However, is this the way a python programmer would do it?

a = [[2,3,4], [9,1,2]]
print map(lambda(i): map(lambda(p): p/10.0,i), a)

And... what if instead of 10, I wanted to use the total of all the values in the nested 2d list?

like image 737
pitosalas Avatar asked Jan 01 '26 15:01

pitosalas


1 Answers

That's generally solved by using comprehensions, in this case a nested list-comprehension:

>>> from __future__ import division   # for python-2.x compatibility
>>> [[item / 10 for item in subl] for subl in a]
[[0.2, 0.3, 0.4], [0.9, 0.1, 0.2]]

That's probably faster than map and avoids all the lambda functions.

what if instead of 10, I wanted to use the total of all the values in the nested 2d list?

Calculate the total using sum and a nested generator expression:

>>> sum_ = sum(item for subl in a for item in subl)
>>> [[item / sum_ for item in subl] for subl in a]
[[0.09523809523809523, 0.14285714285714285, 0.19047619047619047],
 [0.42857142857142855, 0.047619047619047616, 0.09523809523809523]]

But with NumPy arrays it's even easier. NumPy a 3rd party package but very powerful and fast:

>>> import numpy as np
>>> arr = np.array(a)
>>> arr / 10.   # element-wise division
array([[ 0.2,  0.3,  0.4],
       [ 0.9,  0.1,  0.2]])

>>> arr / arr.sum()  # sum over all elements then element-wise division
array([[ 0.0952381 ,  0.14285714,  0.19047619],
       [ 0.42857143,  0.04761905,  0.0952381 ]])
like image 121
MSeifert Avatar answered Jan 03 '26 04:01

MSeifert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!