Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #94478

Re: Find Minimum for element in multiple dimensional array

From Denis McMahon <denismfmcmahon@gmail.com>
Newsgroups comp.lang.python
Subject Re: Find Minimum for element in multiple dimensional array
Date 2015-07-24 00:18 +0000
Organization A noiseless patient Spider
Message-ID <mos086$fpa$1@dont-email.me> (permalink)
References <a7fe6fd3-2a51-40a9-b995-33fc88cb27ee@googlegroups.com>

Show all headers | View raw


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@gmail.com

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Find Minimum for element in multiple dimensional array Robert Davis <rdavis7408@gmail.com> - 2015-07-22 15:54 -0700
  Re: Find Minimum for element in multiple dimensional array Emile van Sebille <emile@fenx.com> - 2015-07-22 16:26 -0700
  Re: Find Minimum for element in multiple dimensional array Robert Davis <rdavis7408@gmail.com> - 2015-07-23 05:31 -0700
  Re: Find Minimum for element in multiple dimensional array Robert Davis <rdavis7408@gmail.com> - 2015-07-23 14:50 -0700
  Re: Find Minimum for element in multiple dimensional array Denis McMahon <denismfmcmahon@gmail.com> - 2015-07-24 00:18 +0000
  Re: Find Minimum for element in multiple dimensional array Robert Davis <rdavis7408@gmail.com> - 2015-07-24 06:17 -0700

csiph-web