Reputation: 17
In my program I get a list that contains an indefinite number of lists, each of these having 4 elements.
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?
Upvotes: 0
Views: 79
Reputation: 69755
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.
Upvotes: 2
Reputation: 3409
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)
Upvotes: 0