我想在 Python 中循环使用三个函数
如何在循环中使用所有 3 个函数?
使用多重处理我也提到了期望的结果
def sum(a, b):
sum= a+b
return sum
def multi(a, b):
mutli= a*b
return multi
def divide(a, b):
divide= a/b
return divide
final_data = [{'a':1, 'b':3},{'a':7, 'b':5},{'a':6, 'b':4}]
for data in final :
sum_value = sum(data['a'], data['b']
multi_value = multi(data['a'], data['b']
divide_value = divide(data['a'], data['b']
#desired final output
final_data = [{'a':1, 'b':3, 'sum_value':4, 'multi_value':3, 'divide_value':0.34},{'a':7, 'b':5,'sum_value':12, 'multi_value':35, 'divide_value':1.4},{'a':6, 'b':4,'sum_value':10, 'multi_value':24, 'divide_value':1.5}]
将问题解释为如何使用异步线程,那么一种可能性可能是:
from multiprocessing.pool import ThreadPool
from functools import partial
import json # used only for output presentation
def run(a, b, func):
s, v = func(a, b)
return s, round(v, 2)
def add(a, b):
return "sum_value", a + b
def multiply(a, b):
return "multi_value", a * b
def divide(a, b):
return "divide_value", a / b
def main():
data = [{"a": 1, "b": 3}, {"a": 7, "b": 5}, {"a": 6, "b": 4}]
with ThreadPool() as pool:
for d in data:
p = partial(run, *d.values())
for s, v in pool.map_async(p, (add, multiply, divide)).get():
d[s] = v
print(json.dumps(data, indent=2))
if __name__ == "__main__":
main()
输出:
[
{
"a": 1,
"b": 3,
"sum_value": 4,
"multi_value": 3,
"divide_value": 0.33
},
{
"a": 7,
"b": 5,
"sum_value": 12,
"multi_value": 35,
"divide_value": 1.4
},
{
"a": 6,
"b": 4,
"sum_value": 10,
"multi_value": 24,
"divide_value": 1.5
}
]