Mehmet KURTOW
Mehmet KURTOW

Reputation: 37

Python List in List trouble

Before start to tell my problem sorry for my grammar and English is not very good. I'm a Python learner. Today i was working on a project but I have a trouble. I'm trying to make a loop.

coordinates = [[1,2],[2,3],[3,5],[5,6],[7,7`],[1,2]]

Here is my list, I'm trying to create a loop. That loop will substract every first values from each others and every seconds to seconds then print. Let me explain my trouble more simple. [[x,y][x1,y1][x2,y2] I need to substract x1-x then print the result after this x2-x1 then print the result but same time y1-y print then print so console output should looks like this;

1,1
1,2
2,1...

Method i've tried

while True:
for x,y in coordinates:
    x = x - y
    print(x)

This is not worked because it substracts x values to y values. I know it's too wrong.

I've research on internet but i did not understand this subject very well. I'm looking for help. Thanks everyone.

Upvotes: 0

Views: 73

Answers (3)

Matthias Fripp
Matthias Fripp

Reputation: 18625

This is fairly similar to your original code:

coordinates = [[1,2],[2,3],[3,5],[5,6],[7,7`],[1,2]]
x_prev = None
for x, y in coordinates:
    if x_prev is not None:
        print('{}, {}'.format(x - x_prev, y - y_prev)
    x_prev, y_prev = x, y

If you want to generalize a bit, for different lengths of coordinates, you could do this:

coordinates = [[1,2],[2,3],[3,5],[5,6],[7,7`],[1,2]]
prev = None
for c in coordinates:
    if prev is not None:
        print(', '.join(c2-c1 for c1, c2 in zip(prev, c)))
    prev = c

Upvotes: 1

Aparna Chaganti
Aparna Chaganti

Reputation: 619

A simple and naive implementation

def pr(arr):
    i = 1
    while i < len(arr):
        (x,y) = arr[i]
        (a,b) = arr[i-1]
        print(x-a, y-b)
        i += 1


if __name__ == '__main__':
    coordinates = [[1,2],[2,3],[3,5],[5,6],[7,7],[1,2]]
    pr(coordinates)

O/P:

1 1
1 2
2 1
2 1
-6 -5

Upvotes: 1

Praveen
Praveen

Reputation: 74

You need to iterate over the list using range function so that you can get current and next ones together. So you can do the subtraction in the loop.

coordinates = [[1,2],[2,3],[3,5],[5,6],[7,7],[1,2]]
for i in range(len(coordinates) - 1):
    print(coordinates[i+1][0] - coordinates[i][0], coordinates[i+1][1] - coordinates[i][1])

Upvotes: 0

Related Questions