Create pairs of points

2133
4
Jump to solution
06-03-2012 04:14 PM
AdamForknall
Occasional Contributor III
Hi there!

I'm trying to create pairs of point features from a point dataset. I'm not really sure on how to get my for loops working to create only 1 instance of each pair.
For example if I have points A, B, C and D, the final pairs would be AB, AC, AD, BC, BD & CD.

My script in its current state is below - this will print all pairs twice except for those containing the first point in the list, which are only printed once. (I hope that makes sense!)

The ultimate aim is to create a table with XY co-ordinates or geometries of each pair, but at this stage I'm just printing the pairs to screen for checking. I'm a complete python (and programming in general) novice and I'd be really grateful if someone could give me so tips on how to make this happen.

Thanks!
Adam

import arcpy  infc =r"D:\POINTS.shp"  #identify geometry field desc = arcpy.Describe(infc) shapefieldname = desc.ShapeFieldName  #Create primary Search Cursor rows = arcpy.SearchCursor(infc)  pointsList = []   count = 0 #iterator counter for testing  #create a list of the points for row in rows:     feat = row.getValue(shapefieldname)     point = feat.getPart()     pointsList.append(point)  count = 0  for point1 in pointsList:     #print point1.X     for point2 in pointsList[1:]:         if point1 != point2:             print (point1,point2)
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
NobbirAhmed
Esri Regular Contributor
Looks like a simpler and better solution already exists in the standard module (pointed out by Jason Scheirer of Esri Geoprocessing team).

# itertools standard module's combinations function does it clearly import itertools  for point1, point2 in itertools.combinations(pointsList, 2):    print point1.X, point2.X


There is no need to create a duplicate list and iterate over two lists.

View solution in original post

0 Kudos
4 Replies
NobbirAhmed
Esri Regular Contributor
Modify the last loop as follows:

# make a duplicate of the original point list
tempPointList = pointList[:]

for point1 in pointsList:

    # remove the current point from the temp list
    tempPointList.remove(point1)

    for point2 in tempPointList:
        
        # point1 and point2 to make a pair
        print (point1.X, point2.X)
0 Kudos
AdamForknall
Occasional Contributor III
Genius! Thanks Nobbir!

😄
0 Kudos
NobbirAhmed
Esri Regular Contributor
Looks like a simpler and better solution already exists in the standard module (pointed out by Jason Scheirer of Esri Geoprocessing team).

# itertools standard module's combinations function does it clearly import itertools  for point1, point2 in itertools.combinations(pointsList, 2):    print point1.X, point2.X


There is no need to create a duplicate list and iterate over two lists.
0 Kudos
AdamForknall
Occasional Contributor III
Brilliant! That makes the code much simpler. Thanks!
0 Kudos