emax emax - 6 months ago 11
Python Question

Python: how to avoid a loop for normalizing a list of list?

I have a list

X
containing the data of
N
users. I want to have the relative frequency distribution of each user.

l1 = list()
for i in range(0,N):
tmp = np.array(X[i])
tmp = tmp[tmp < tr]
tmp = np.histogram(tmp, x)
l1.append(tmp[0]/sum(tmp[0]))


Is there any way to avoid this loop?

Answer

Use map:

def op(A):
    tmp = np.array(A)
    tmp = tmp[tmp < tr]
    tmp = np.histogram(tmp, x)
    return tmp[0]/sum(tmp[0])

# creates a generator
map(op, X)
# or, to get a list
l1 = list(map(op, X))