Find Minimum for element in multiple dimensional array

Emile van Sebille emile at fenx.com
Thu Jul 23 01:26:58 CEST 2015


On 7/22/2015 3:54 PM, Robert Davis wrote:
> I have an array of arrays that have a origin zip code, origin latitude, origin longitude, destination zip code, destination latitude, destination longitude, and miles between the two points.
>
> I need to keep only those combinations that represent the minimum mileage between to the destination zip code. For example a point in New Jersey may have a distance from the Philadelphia Office that is 45 miles, from the Newark Office that is 78 miles and one from the Delaware Office that is 58 miles.
>
> I need to keep the mileage from the Philadelphia Office that is 45 miles and produce a .csv file that has origin zip code, origin latitude, origin longitude, destination zip code, destination latitude, destination longitude, and miles between the two points.
>
> The array looks like this:
>
> [['37015', 'TN31', 36.2777, -87.0046, 'NY', 'White Plains', '10629', 41.119008, -73.732996, 77.338920003],
> ['72202', 'ARB1', 34.739224, -92.27765, 'NY', 'White Plains', '10629', 41.119008, -73.732996, 1099.7837975322097]]

Assume the array in A:

---8<---8<---8<---8<---8<---8<---8<---8<---8<---8<---
A= [['37015', 'TN31', 36.2777, -87.0046, 'NY', 'White Plains', '10629', 
41.119008, -73.732996, 77.338920003],
  ['72202', 'ARB1', 34.739224, -92.27765, 'NY', 'White Plains', '10629', 
41.119008, -73.732996, 1099.7837975322097]]

# transform to a dict ignoring dups
D = dict( [ ( ((r[6],r[0]),r[-1]), r) for r in A ] )

# convert to a sorted list
L = sorted(D.items())

# then print and filter out any duplicated entries
lastzippair = (None,None)

for ky,rec in L:
     if ky[:2] == lastzippair:
         continue
     print ky,":",rec
     lastzippair=ky[:2]

---8<---8<---8<---8<---8<---8<---8<---8<---8<---8<---

The results are what you'd write to the csv file.

Tested only with the data you provided.

HTH,

Emile




More information about the Python-list mailing list