Search code examples
pythonpython-3.xcoordinatespoints

Renaming points in python


I have a collection of new points i,j,k,l with their coordinates (1953.2343076828638, 730.0513627132909), (1069.4232335022705, 5882.057343563125),(2212.5767664977293, 3335.942656436875),(4386.765692317136, 1318.948637286709).

I'm trying to give these points some names as s1,s2,s3,s4.

Also, create two separate lists one with just the point name [s1,s2,s3,s4] and the other one with point name and its coordinate as [s1:(1953.2343076828638, 730.0513627132909),(1069.4232335022705, 5882.057343563125)...]

I have the following code for creating random points.

n = 10
#print(n)

#for k in n:
V = []
V=range(n)
#print("vertices",V)

# Create n random points

random.seed()

pos = {i:(random.randint(0,4000),random.randint(0,5000)) for i in V}
#print("pos =", pos)

points = []
positions = []
for i in pos:
    points.append(pos[i])
    positions.append(i)
    positions.append(pos[i])

Suppose I am forming a new list L with two existing points 4 and 7.Then, L = [4,7]

When I type L[0] in the console it gives me, 4 and pos[L[0]] gives me its coordinates.

But considering my new list K= [i,j,k,l], when I type K[0] in the console it gives me the coordinate, but not its name.

I need to add these points in K to the same list as pos defined above with their coordinates, but with different names. Can someone please help me with this?


Solution

  • To access name and coordinates by index, use a list of tuples. Note that you need to name these explicitly. You should preferably avoid this step by using a list of tuples to store your name-coordinate pairs from the beginning.

    To access by name, use a dictionary.

    i, j, k, l = (1953.2343076828638, 730.0513627132909),\
                 (1069.4232335022705, 5882.057343563125),\
                 (2212.5767664977293, 3335.942656436875),\
                 (4386.765692317136, 1318.948637286709)
    
    K = [(name, var) for name, var in zip('ijkl', (i, j, k, l))]
    
    ## ACCESS BY INDEX
    name_coord = K[0]  # ('i', (1953.2343076828638, 730.0513627132909))
    name = K[0][0]  # 'i'
    coord = K[0][1]  # (1953.2343076828638, 730.0513627132909)
    
    ## ACCESS BY NAME
    d = dict(K)
    coord = d['i']  # (1953.2343076828638, 730.0513627132909)