I'm currently doing a school project where I need to code a program in python that subtracts a value from a list of coordinates.
I'm not allowed to use import
to make things easier.
I have the list: [[1,2],[2,3],[3,4]]
and I need to subtract a value from the second value in each list inside this list.
So for an example: [[1,2],[2,3],[3,4]]
becomes: [[1,1],[2,2],[3,3]]
This is the code I have thus far:
def coordinates(y):
for i in (y):
(i[1] - 5)
return (y)
I just can't get it to work though. Does anyone know a good way to do this?
CodePudding user response:
Given you're attempting to always subtract from the y coordinate, indexing into the list's set of lists would provide the easiest solution to your problem.
The following subtracts 1 from the lists second coordinate and returns the list.
def coordinates(l):
for i in range(len(l)):
l[i][1] = l[i][1] - 1
return l
CodePudding user response:
Let's assume that you don't want to modify the original list. In that case:
def coordinates(l):
return [[x, y-1] for x, y in l]
print(coordinates([[1,2],[2,3],[3,4]]))
Output:
[[1, 1], [2, 2], [3, 3]]
CodePudding user response:
I think you should make your function generic by passing everything it needs to know to is as arguments instead of hardcoding everythings into it — which will allow it to be reused with different lists and/or amounts.
This following illustrates what I mean:
def add_y(coords, y):
for coord in coords:
coord[1] = y
return coords
data = [[1,2],[2,3],[3,4]]
print(data) # -> [[1, 2], [2, 3], [3, 4]]
data = add_y(data, -1)
print(data) # -> [[1, 1], [2, 2], [3, 3]]