Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplify a loop in python

I am using this loop in my python code:

final_fun=[]
for i_base in xrange(n_base):
  final_fun.append(sum(fun[:,i_base])/n_ci)

and I would want to know how I can simplify this loop? If I simplify this loop will my program be faster? In general I know how to simplify this but here I am blocked by the append!

like image 331
PanAkry Avatar asked Sep 26 '26 08:09

PanAkry


2 Answers

Use list comprehensions. It's faster and cleaner. The interpreter can be slowed down a lot by the for loop, and there's nothing to lose by simply rearranging the syntax.

See this explanation for more details.

final_fun = [sum(fun[:,i_base])/n_ci for i_base in xrange(n_base)]
like image 68
Rob Volgman Avatar answered Sep 28 '26 22:09

Rob Volgman


It seems fun is a two-dimensional NumPy array. In this case, you can simplify and speed up the code significantly by completely avoiding the Python loop:

final_fun = fun.sum(axis=0) / n_ci

You will end up with a NumPy array instead of a list, but chances are this is what you want anyway.

like image 32
Sven Marnach Avatar answered Sep 28 '26 22:09

Sven Marnach



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!