gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:27:45 25 4
gpt4 key购买 nike

给定:

xvalues = [0.0, 1829.0, 3658.0, 5487.0]

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

我想循环nodesF并返回x1x2每个 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 for value in xvalues if value > x) ValueError: min() arg is an empty sequence.

所以我的问题是如何传递这个错误?如果我可以设置 x2=Nonemin()是空的就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

关于python - 假设 x 属于 [x1,x2],则获取 x1,x2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21005296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com