I am measuring the closest straight distance from cities of interest (in a layer) to their capital cities (in another layer). Basically, distance between a city and a capital city is calculated if only if their country codes are identical. Arcgis license is advanced.
Solution:
The following solution is based on @dklassen. Modification has been made so that I can loop a list of numerical number.
import arcpy
ctryID = [row.ID_0 for row in arcpy.SearchCursor(countryID_feature_class)]
arcpy.MakeFeatureLayer_management('PATH_TO_CITIES_FC','cityfc')
arcpy.MakeFeatureLayer_management('PATH_TO_CAPITALS_FC','capitalfc')
for grd in ctryID:
arcpy.SelectLayerByAttribute_management('cityfc','NEW_SELECTION',""""ID_0" = {}""".format(grd))
arcpy.SelectLayerByAttribute_management('capitalfc','NEW_SELECTION',""""ID_0" = {}""".format(grd))
arcpy.Near_analysis('cityfc','capitalfc',"#","NO_LOCATION","NO_ANGLE")
arcpy.CopyFeatures_management("cityfc", "c:/temp/ctry{}".format(grd))
arcpy.CreateFeatureclass_management("c:/temp/", "ctryall.shp", "POINT", "c:/temp/ctry1.shp", "DISABLED", "DISABLED")
for grd in ctryID:
arcpy.Append_management("c:/temp/ctry{}.shp".format(grd), "c:/temp/ctryall.shp")
arcpy.Delete_management("c:/temp/ctry{}.shp".format(grd))