user3880665
user3880665

Reputation: 5

Creating line segment lists from x,y lists in Python

I want to coordinate data for rectangles is given in two lists (e.g.):

x = [1, 8, 9, 4]  
y = [2, 3, 6, 7] 

I want to create a list of the line segment endpoints representing the rectangles. It would be ideal if the list was in the form:

segment_endpoints = [((1, 2), (8, 3)), ((8, 3), (9, 6)), ((9, 6), (4, 7)), ((4, 7), (1, 2))]

My attempt:

vertices = zip(x, y)  
segment_endpoints = zip(vertices, vertices[1:] + [vertices[0]])  

But Python will not let me zip a zipped object.

Surely there is an easy way to do this. New to programming. New to stackoverflow.

Upvotes: 0

Views: 377

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

In Python 3 when using zip you need to use list(zip()):

In [10]: vertices = list(zip(x, y))

In [11]: list(zip(vertices, vertices[1:] + [vertices[0]]))
Out[11]: [((1, 2), (8, 3)), ((8, 3), (9, 6)), ((9, 6), (4, 7)), ((4, 7), (1, 2))]

In python3 zip returns an iterator as opposed to a list in python2 so you need to use the list(zip()) syntax.

Upvotes: 2

Related Questions