简体   繁体   中英

Get x1,x2 provided that x belongs to [x1,x2]

Given:

xvalues = [0.0, 1829.0, 3658.0, 5487.0]

and

nodesF = [[1, 0, 0, 0], [2, 0.5, 0, 0], [3, 5487, 0, 0]]

I want to loop over nodesF and return x1 and x2 values which every x of nodesF lie between, ie x belongs to [x1,x2] with x1<x2 .

My code is:

     for nodeID, x, y, z in nodesF:
        x2= min(value for value in xvalues if value >= x)
        x1= max(value for value in xvalues if value <= x)
        if x1==x2:
            x1=None
            x2=None
            x2= min(value for value in xvalues if value > x)
            x1= max(value for value in xvalues if value <= x)
            if x2==None or x2<=x1:
                x2= min(value for value in xvalues if value >= x)
                x1= max(value for value in xvalues if value < x)
            elif x1==None or x2<=x1:
                print "Error"

For x=5487 I get:

x2= min(value for value in xvalues if value > x) ValueError: min() arg is an empty sequence.

So my question is how do get pass this error? if I could just set x2=None when min() is empty it would be OK! Thanks!

You're on the right track, but you'll need to do the check the list yourself:

valid_values = [value for value in xvalues if value > x] #changed >= by >
if valid_values:
    x2 = min(valid_values)
else:
    x2 = None

Or you could catch the error after the fact:

try:
    x2 = min(value for value in xvalues if value > x) #changed >= by >
except ValueError:
    x2 = None

So two lines might seem a little terse, but I hope you like it:

r = zip([float('-inf')] + xvalues, xvalues + [float('inf')])

which produces this:

In [104]: print r
Out[104]: [(-inf, 0.0), (0.0, 1829.0), (1829.0, 3658.0), (3658.0, 5487.0), (5487.0, inf)]

Then get your ranges like this:

[[filter(lambda l: l[0] < n <= l[1], r)[0] for n in m] for m in nodesF]

which produces this:

Out[102]: 
[[(0.0, 1829.0), (-inf, 0.0), (-inf, 0.0), (-inf, 0.0)],
[(0.0, 1829.0), (0.0, 1829.0), (-inf, 0.0), (-inf, 0.0)],
[(0.0, 1829.0), (3658.0, 5487.0), (-inf, 0.0), (-inf, 0.0)]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM