Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

python - Function to subtract each element in a list

I’m attempting to make a function to subtract each element from a list in python, however, the first element must be nan.

This is my function:

def sub_vector(x):
  from numpy import nan
  
  y=[]
  for j, i in enumerate(range(len(x)-1)):
      z= np.nan
      if j == 0:
          y.append(z)
          
      else:
        val = x[i+1] - x[i]
        y.append(val)
  return y

The response should be such as:

zz = [1, 2, 3, 4, 5]  
sub_vector(zz)  
[nan, 1, 1, 1 ,1]  
But this function is returning:  
[nan, 1, 1, 1]

What is my mistake?

question from:https://stackoverflow.com/questions/65906610/function-to-subtract-each-element-in-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
from numpy import nan

def sub_vector(x):
    return [nan] + [x[i] - x[i - 1] for i in range(1, len(x))]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...