gpt4 book ai didi

python - 从循环中的函数返回两个值

转载 作者:行者123 更新时间:2023-12-01 04:18:28 24 4
gpt4 key购买 nike

我有一个功能:

def func(a,b,c):
result = a+b+c
error = np.sqrt(a+b+c)
return result, error

但是,我有多对 a、b、c,我用它们来调用函数:

parameters = [(a1,b1,c1),
(a2,b2,c2),
(a3,b3,c3)]

final_result,final_error = [func(*args) for args in parameters]

我收到错误ValueError:太多值无法解压

如何让 final_resultfunc 中包含 result 的所有值,并且 final_error 的值相同> ?

如果我打电话

results = [func(*args) for args in parameters]

它工作正常,但结果现在包含错误和结果!

我希望 final_result 包含不同参数的 a+b+c 值,并让 final_error 包含 值>np.sqrt(a+b+c)

最佳答案

#!/usr/bin/env python3
# coding: utf-8

import numpy as np

def func(a, b, c):
result = a+b+c
error = np.sqrt(a+b+c)
return result, error

parameters = [(3,2,1),
(4,5,6),
(7,8,9)]

l = [func(*p) for p in parameters]
final_result, final_error = zip(*l)

print(l)
print(final_result)
print(final_error)

给予:

[(6, 2.4494897427831779), (15, 3.872983346207417), (24, 4.8989794855663558)]
(6, 15, 24)
(2.4494897427831779, 3.872983346207417, 4.8989794855663558)

关于python - 从循环中的函数返回两个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34024151/

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