emax emax - 1 year ago 85
Python Question

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

I have a list

containing the data of
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)

Is there any way to avoid this loop?

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download