[英]Get x1,x2 provided that x belongs to [x1,x2]
鑒於:
xvalues = [0.0, 1829.0, 3658.0, 5487.0]
和
nodesF = [[1, 0, 0, 0], [2, 0.5, 0, 0], [3, 5487, 0, 0]]
我想循環遍歷nodesF
並返回x1
和x2
值,每個nodesF
x
nodesF
位於它們之間,即x屬於[x1,x2]
且x1<x2
。
我的代碼是:
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"
對於x = 5487我得到:
x2 = min(如果value> x,則為xvalues中value的值)ValueError:min()arg為空序列。
所以我的問題是如何通過此錯誤? 如果當min()
為空時我只能將x2=None
設置為OK! 謝謝!
您的路線正確,但是您需要自己檢查清單:
valid_values = [value for value in xvalues if value > x] #changed >= by >
if valid_values:
x2 = min(valid_values)
else:
x2 = None
或者您可以在事實發生后捕獲錯誤:
try:
x2 = min(value for value in xvalues if value > x) #changed >= by >
except ValueError:
x2 = None
因此,兩行似乎有點簡潔,但我希望您喜歡它:
r = zip([float('-inf')] + xvalues, xvalues + [float('inf')])
產生這個:
In [104]: print r
Out[104]: [(-inf, 0.0), (0.0, 1829.0), (1829.0, 3658.0), (3658.0, 5487.0), (5487.0, inf)]
然后得到這樣的范圍:
[[filter(lambda l: l[0] < n <= l[1], r)[0] for n in m] for m in nodesF]
產生這個:
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.