Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list element wise conditional increment

I have been searching this for a while, basically I am trying to conditionally increment a list of element by another list, element-wise...

my code is following, but is there a better way to do it? list comprehension, map??

I think a element-wise operator like ~+= from http://www.python.org/dev/peps/pep-0225/ would be really good, but why is it deferred?

for i in range(1,len(s)):
        if s[i]<s[0]:
            s[i]+=p[i]

based on some good feedbacks from you guys I have recoded to the following

i=s<s[0]
s[i]+=p[i]

and s,p are both arrays.

p.s still slow than matlab 5 times for one of my code.

like image 424
Jerry Gao Avatar asked Jun 19 '26 22:06

Jerry Gao


2 Answers

Here is a quick version:

# sample data
s = [10, 5, 20]
p = [2,2,2]

# As a one-liner.  (You could factor out the lambda)
s = map(lambda (si, pi): si + pi if si < s[0] else si, zip(s,p))

# s is now [10, 7, 20]

This assumes that len(s) <= len(p)

Hope this helps. Let me know. Good luck. :-)

like image 140
nonot1 Avatar answered Jun 22 '26 11:06

nonot1


If you don't want to create a new array, then your options are:

  1. What you proposed (though you might want to use xrange depending on the python version)
  2. Use Numpy arrays for s and p. Then you can do something like s[s<s[0]] += p[s<s[0]] if s and p are the same length.
  3. Use Cython to speed up what you've proposed.
like image 31
Justin Peel Avatar answered Jun 22 '26 11:06

Justin Peel



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!