Python element list element wise conditional increment

I searched for this for a while, basically I'm trying to conditionally increase the list of elements with another list, element-wise ...

my code is the following, but is there a better way to do this? list, map?

I think an elementary statement like ~ + = from http://www.python.org/dev/peps/pep-0225/ would be really good, but why is it postponed?

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

based on some good reviews from you guys I transcoded the following

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

and s, p are both arrays.

ps is still slower than matlab 5 times for one of my codes.

+3
source share
4 answers

If you do not want to create a new array, then your options are:

  • ( xrange python)
  • Numpy s p. - s[s<s[0]] += p[s<s[0]], s p .
  • Cython, , .
+1

:

# 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]

, len(s) <= len(p)

, . . .: -)

+2

:

, - :

[sum(a) for a in zip(*[s, p]) if a[0] < 0]

:

>>> [sum(a) for a in zip(*[[1, 2, 3], [10, 20, 30]]) if a[0] > 2]
[33]

, zip:

>>> zip(*[[1, 2, 3], [4, 5, 6]])
[(1, 4), (2, 5), (3, 6)]

( ) . .

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

Source: https://habr.com/ru/post/1775536/


All Articles