0

Hi I'm trying to write a function which has an input that is a 2D array set up like a list of lists. The first two columns of the array are ID numbers but the remaining 12 columns indicate how many hours each employee has worked each month. I want to find the month to month deviation of each employee, however, the code I am currently working with is a little unrefined. Its output is a single list of the differences between all the numbers (the IDs included). I am trying to get the output to be a list for each row in the 2D array with the ID numbers followed by the month to month deviations (the first month would always be zero because there is no previous month to subtract it from):

[123, 34567, 0, 3, 4, 12, 13, 5, 8, 10, 11, 19, 2, 6] 

My code is currently as follows:

def month_to_month(A):
X = []
for i in range(len(A)):
    for j in range(len(A[i])):
        X += [abs(A[i][j] - A[i][j-1])]
return X

Where the function iterates over each row first, and then each column, finding the absolute difference between column values and adding those values to the list X. I need help refining this, however, where only the monthly values are subtracted, and the output returns each employee's data as an individual list, as seen in the example above. I tried using recursion to subtract the consecutive column values but that did not work very well. I really appreciate any input!

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
user3758443
  • 149
  • 1
  • 3
  • 10
  • Could you post an example with input and desired output? – igon Jul 02 '14 at 00:36
  • Sure the input would be a list of lists: [[123, 34567, 50, 53, 49, 61, 48, 53, 61, 71, 60, 79, 81, 87],...] – user3758443 Jul 02 '14 at 00:40
  • And the output would be [123, 34567, 0, 3, 4, 12, 13, 5, 8, 10, 11, 19, 2, 6]. So it retains the first two elements of the inner list but shows the deviation between each of the remaining values – user3758443 Jul 02 '14 at 00:41

1 Answers1

0
def month_to_month(self):
    A = [123, 34567, 50, 53, 49, 61, 48, 53, 61, 71, 60, 79, 81, 87] 
    B = A[-(len(A) - 2):]
    X = [A[0], A[1], 0]
    X.extend([abs(j-i) for i,j in zip(B, B[1:])])
    print(X)

I put this answer together after seeing a similar question Python - Differences between elements of a list

Community
  • 1
  • 1
Budoray
  • 155
  • 2
  • 2
  • 10