Determine the indices of a vector to be subtracted

Asked

Viewed 50 times

0

I have the following vector:

a = [10, 20, 30, 40, 50, 60...]

I need to create a new list that is the subtraction of the later index by the previous one. For example:

b = [indice[0] - indice[1], indice[2] - indice[3], indice[4] - indice[5]...]

In this case, I need to have the values:

b = [10, 10, 10...]

Could someone help me by telling me how I do it?

Grateful for the help.

3 answers

1

See working here.

a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]
b = []

# i = indice anterior
i = 0
# p = proximo indice
p = 1
# Divide o tamanho total por 2
total = len(a) / 2
for x in xrange(0, len(a)):
  if x < total:
    b.append((a[p] - a[i]))
    i += 2
    p += 2

print(b)
  • Thank you very much!

1

Follow an example:

a = [10, 20, 50, 80, 50, 60];
b = [];

for i in range(len(a)):
  if (i+1) < len(a):
    b.append(a[i+1]-a[i]);
    del(a[i])

print (b);
  • Thank you very much!

1


Be it to an array. Using comprehensilist on, do:

a = [10, 20, 50, 80, 50, 60]
b = [a[i+1]-a[i] for i in range(0,len(a),2) if i+1 < len(a) ]
print b

In this way, we are only iterating the two-by-two elements.

  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.