Home > OS >  Make a list of lists from another by making successive subtractions of their rows
Make a list of lists from another by making successive subtractions of their rows

Time:10-29

In my program I get a list of lists of always 4 elements each with an indefinite number of lists.

Example:

List=[[70,70,70,70],[1,1,1,1],[2,2,2,2],[4,4,4,4]]

I would like by means of a function to be able to subtract the values and have the result instead. Resulting:

Result_List=[[70,70,70,70],[69,69,69,69],[67,67,67,67],[63,63,63,63]]

The idea would be that the result of the first row is the same, in the second row the subtraction of the first row minus the second is done, in the third row the values of the second row are done minus the third and so on regardless the number of rows. The number of columns is constant. How could I do it?

CodePudding user response:

You can use the following code:

List = [[70,70,70,70],[1,1,1,1],[2,2,2,2],[4,4,4,4]]
result = [List[0]] # add the first element since it doesn't change

for sub_list in List[1:]: # for each element omitting the first one
    result.append(
        [
            # subtract the current element of List (iteration)
            # to the latest element of result
            e1 - e2
            for e1, e2 in zip(result[-1], sub_list) 
        ]
    )

print(result)

Output

[[70, 70, 70, 70], [69, 69, 69, 69], [67, 67, 67, 67], [63, 63, 63, 63]

The key element is the use of zip which allows us to iterate 2 collections in parallel.

CodePudding user response:

A less efficient answer, but designed to be (hopefully) easier to understand for a beginner:

List = [[70,70,70,70],[1,1,1,1],[2,2,2,2],[4,4,4,4]]

New_List = [List[0]] # Make a new list that already contains the first sublist

for i in range(1, len(List)):
    sublist = []
    for j in range(4):
        # New_List[-1] is the last sublist in New_List
        sublist.append(New_List[-1][j] - List[i][j])
    New_List.append(sublist)
    
print(New_List)
  • Related