Determine the indices of a vector that must be subtracted

0

I have the following vector:

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

I need to create a new list that is subtracting the previous index from the previous one. For example:

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

In this case, I have to answer the values:

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

Could someone help me by saying how do I do this?

Thanks for the help.

    
asked by anonymous 18.08.2017 / 04:35

3 answers

1

Be to an array. Using list comprehension , we 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 elements two by two.

    
18.08.2017 / 05:33
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)
    
18.08.2017 / 05:00
1

Here's 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);
    
18.08.2017 / 05:08