简体   繁体   English

假设x属于[x1,x2],则获取x1,x2

[英]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 . 我想循环遍历nodesF并返回x1x2值,每个nodesF x nodesF位于它们之间,即x属于[x1,x2]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: 对于x = 5487我得到:

x2= min(value for value in xvalues if value > x) ValueError: min() arg is an empty sequence. x2 = min(如果value> x,则为xvalues中value的值)ValueError:min()arg为空序列。

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! 如果当min()为空时我只能将x2=None设置为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)]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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