Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is not exactly the answer you were looking for, but this is my 50c answer...</p> <pre> A = {1:'a1',2:'a2',3:'a3',4:'a4'} B = {0.7:'b1',0.9:'b2',1.7:'b3',2:'b4', 2.4:'b5'} C = {} # result # find altitude in A that is the closest to altitude in B def findAltitude( altB,A): toto = [ ((alt-altB)**2,alt) for alt in A.keys() ] toto.sort() return toto[0][1] #iter on each altitude of B for altB,valueB in B.iteritems(): altC = findAltitude( altB,A) if altC in C: C[altC].append(valueB) else: C[altC] = [valueB,] # then do the median operation #for altC,valueC in C.iteritems(): # C[altC] = map( median, valueC ) # where median is your median function print C </pre> <p>It is NOT the best solution at all (specially if you have a lot of values), but only the fastest to write...</p> <p>In fact, it depends how your datas are stored. Dictionnary is not the best choice.</p> <p>It is more interesting/clever to use the fact that your altitudes are sorted. You should provide more details on how your datas are stored (array with numpy ?) </p> <p>==== Edit ====</p> <p>I still do not know how your datas are, but let's try something more "clever", based on the fact that your altitudes are sorted.</p> <pre><code>from numpy import * from pylab import * from scipy.stats import nanmedian # add val into C at the end of C or in the last place (depending if alt already exists in C or not) def addto(C,val,alt): if C and C[-1][0]==alt: C[-1][1].append(valB) else: C.append( (alt,[valB,] )) # values A_Alt = array([1,2,3,4]) A_Val = array([.33, .5, .6, .8]) B_Alt = array([.7, 0.9, 1.7, 2., 2.4, 2.9, 3.1, 3.2, 3.9, 4.1]) B_Val = array([.3, NaN, .8, .6, .7, .4, .3, NaN, .99, 1.3]) #intermediate list of tuple (altitude, list_of_values) C= [] #iterator on A Aa = iter(A_Alt) ainf = Aa.next() asup = Aa.next() # two first values of A_Alt #iterator on B Ba = iter(B_Alt) Bv = iter(B_Val) # regrid try: while True: altB = Ba.next() valB = Bv.next() # find ainf and asup in A_Alt such that ainf &lt; altB &lt; asup while asup&lt;altB: try: ainf,asup = asup, Aa.next() except StopIteration: break # find closest if abs(ainf-altB)&lt;=abs(asup-altB): addto(C, valB, ainf) else: addto(C, valB, asup) except StopIteration: pass # do the median res = [ nanmedian(k[1]) for k in C ] print res </code></pre> <p>The idea is then to iterate over the two vectors/lists of altitudes, and for each altitude of B, find the two altitudes of A that surround it. Then, it is easy to find the closest...</p> <p>This is less readable than Daan's solution, but it should be more efficient (linear in the size of your datas).</p> <p>You just need to modify if your datas are not stored like that.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload