[英]return the first element with a difference from two lists of lists and stop to compare
我在 python 上从事一个项目,我需要返回两个列表列表之间的第一个增量(差异)。 而里面的每一个position都是指一个名字。
我成功地返回了每个参数的第一个增量,但我想在第一个带有增量的子列表处停止。
我的实际代码是:
l_name = ["TIME", "ALPHA", "BETA"] # the list of names
liste1 = [[1, 2, 3.0], [2,5.045,6.003], [3, 8.03, 9], [4, 10.5, 5.5]] # values of all name in one sublist by step time
liste2 = [[1, 2, 3.0], [2,5.045,6.005], [3, 8.0029, 9], [4, 10.5, 5.5555]]
abs_tol = 0.00001 # tolerence to found a delta
def search_var_delta():
for i in range(len(l_name)):
for k in range(len(liste1)):
a = liste1[k][i]
b = liste2[k][i]
diff = abs(a-b)
if diff >= abs_tol :
print("the delta : {}".format(diff),
"the index : {}".format(k+1),
"the parameter : {}".format(l_par[i]))
break
search_var_delta()
我使用 break 来停止比较子列表,但它继续比较下一个子列表。
Output:
('the delta : 0.0271', 'the index : 3', 'the parameter : ALPHA')
('the delta : 0.002', 'the index : 2', 'the parameter : BETA')
但我只想:
('the delta : 0.002', 'the index : 2', 'the parameter : BETA')
因为它是第一个带有增量的索引
如果我添加return l_par[i]
,它将打印 ALPHA 一个,但正如我们所见,它位于索引 3 中,因此不在带有增量的第一个子列表中。
通常它是通过围绕内循环的标志完成的,但在 Python 中你可以使用for... else :
def search_var_delta():
for i in range(len(l_name)):
for k in range(len(liste1)):
# ...
if diff >= abs_tol :
# ...
break
else:
continue
break
诀窍是else
语句中的代码在内部for
循环终止时执行,而不是在它被break
语句终止时执行。
你可以这样做:
l_name = ["TIME", "ALPHA", "BETA"]
liste1 = [[1, 2, 3.0], [2,5.045,6.003], [3, 8.03, 9], [4, 10.5, 5.5]]
liste2 = [[1, 2, 3.0], [2,5.045,6.005], [3, 8.0029, 9], [4, 10.5, 5.5555]]
tolerance = 0.00001
def process():
for i, v in enumerate(zip(liste1, liste2), 1):
for j in range(len(v[0])):
if (delta := abs(v[0][j]-v[1][j])) > tolerance:
print(f'Delta = {delta:.3f}, index = {i}, parameter = {l_name[j]}')
return
process()
[注意:你需要 Python 3.8+]
注意:抱歉 l_par 是 l_name 的错误。 我忘记改名字了。
好吧,答案很简单抱歉,
它只需要反转for循环并使用return:
def search_var_delta():
for k in range(len(liste1)):
for i in range(len(l_name)):
a = liste1[k][i]
b = liste2[k][i]
diff = abs(a-b)
if diff >= abs_tol :
print("the delta : {}".format(diff),
"the index : {}".format(liste1[k][0]),
"the parameter : {}".format(l_name[i]))
return [diff, liste1[k][0], l_name[i]]
search_var_delta()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.