-1

Say I have N lists of size n, eg, 5 tuples of size 3:

p = [[9, 9, 9], [17, 14, 18], [14, 15, 17], [14, 15, 17], [14, 15, 15]]

How can I find the difference between indexes of the lists, for example the index 0:

17-9 = 8
14-17 = -3
14-14 = 0
14-14 = 0

then for index 1:

14-9 = 5
15-14 = 1
15-15 = 0
15-15 = 0

then index 2, 3, 4.

I need the code to be able to do this dynamically so I can change N and n at will.

Any help will be greatly appreciated.

EDIT:

I have tried this thus far:

for i in range(10):
    for j, k in product(range(i+1), repeat=2):
        if j!=k:continue
        else:
            print p[i][j]-p[i-1][j]

This code is for tuples of size 2.

Sameer Patel
  • 927
  • 3
  • 16
  • 20
  • 1
    These are not tuples. Tuples are in parens, like `(9, 9, 9)`. – ulidtko Mar 20 '13 at 15:07
  • 1
    It would be helpful to know what you've tried and also what you're looking for in a solution (e.g. most pythonic way of doing it, fastest, easiest to read?) – Emily Mar 20 '13 at 15:08
  • what the format of the data you expect ? a list of list too ? – ornoone Mar 20 '13 at 15:09

5 Answers5

2

Try this:

>>> for x in zip(*p):
    for i in range(len(x)-1):
        print '{0} - {1} = {2}'.format(x[i+1],x[i],x[i+1]-x[i])


17 - 9 = 8
14 - 17 = -3
14 - 14 = 0
14 - 14 = 0
14 - 9 = 5
15 - 14 = 1
15 - 15 = 0
15 - 15 = 0
18 - 9 = 9
17 - 18 = -1
17 - 17 = 0
15 - 17 = -2
pradyunsg
  • 18,287
  • 11
  • 43
  • 96
1

ugly as hell, not pythonic, prone to all the errors of this world, but yet working (and at least should show you a basic logic for what you need):

In [6]: for i in range(len(p[0])):
            for j in range(1,len(p)):
               print "%d - %d = %d" % (p[j][i], p[j-1][i], p[j][i]-p[j-1][i])
   ...:         
17 - 9 = 8
14 - 17 = -3
14 - 14 = 0
14 - 14 = 0
14 - 9 = 5
15 - 14 = 1
15 - 15 = 0
15 - 15 = 0
18 - 9 = 9
17 - 18 = -1
17 - 17 = 0
15 - 17 = -2

explanation

  • row 1: checks for the length of your sublists, based on the first element of your max list.

  • row 2: does the same, starting from index one (so you can do p[1]-p[0] without worrying about out of bounds problems)

  • row 3: prints what you want

you could start from this to tinker around

Samuele Mattiuzzo
  • 10,760
  • 5
  • 39
  • 63
1

This should do it:

for xyz in zip(*p):
   for curr_idx in xrange(len(xyz)-1):
     print xyz[curr_idx+1]-xyz[curr_idx]
1

It can easily be done using numpy:

p = numpy.array([[9, 9, 9], [17, 14, 18], [14, 15, 17], [14, 15, 17], [14, 15, 15]])
numpy.diff(p.T)
Charles Brunet
  • 21,797
  • 24
  • 83
  • 124
1

try this

p = ((9, 9, 9), (17, 14, 18), (14, 15, 17), (14, 15, 17), (14, 15, 15))
index=0
for d in range(1,len(p)):
    print "p["+str(d)+"]["+str(index)+"]-p["+str(d)+"]["+str(index)+"]=",
    print p[d][index]-p[d-1][index]

output is

p[1][0]-p[1][0]= 8
p[2][0]-p[2][0]= -3
p[3][0]-p[3][0]= 0
p[4][0]-p[4][0]= 0
Mahdi-bagvand
  • 1,396
  • 19
  • 40