Find Minimum for element in multiple dimensional array

Denis McMahon denismfmcmahon at gmail.com
Fri Jul 24 02:18:15 CEST 2015


On Wed, 22 Jul 2015 15:54:06 -0700, Robert Davis wrote:

> Given a set of arrays within an array how do I find the arrays with the
> minimum values based on two elements/columns in the array? Those two
> elements/columns are the destination zip code and distance.

create a new dictionary

for each source/destination pair in your list of source destination pairs:

if the destination zip code is not in the new dictionary, copy the entry 
to the new dictionary keyed on the destination zip code.

if the destination zip code is in the new dictionary, copy the entry to 
the new dictionary keyed on the destination zip code only if the distance 
is less than the distance of the current entry in the new dictionary.

convert the values of the new dictionary to a list.

write the list as csv

Here is an example, note that I'm just using 2 bits of data, the first 
bit of data in each sub list simulates the destination area code, and the 
second simulates the distance from the associated source zip code. 
Obviously you need to adjust these to match the actual parameters in your 
list of lists.

import csv

info = [['a',15],['a',17],['a',21],['b',96],['b',45],['b',38],['c',71],
['c',18],['c',54]]

tmp = {}

for thing in info:
    if thing[0] in tmp:
        if thing[1] < tmp[thing[0]][1]:
            tmp[thing[0]] = thing
    else:
        tmp[thing[0]] = thing

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(tmp.values())

and lo:

$ cat output.csv
a,15
c,18
b,38
$ 


-- 
Denis McMahon, denismfmcmahon at gmail.com


More information about the Python-list mailing list