gpt4 book ai didi

python - 如何仅运行一次具有多个值的 def 并将值使用到另一个 def 中?

转载 作者:行者123 更新时间:2023-11-30 22:50:23 27 4
gpt4 key购买 nike

我的问题非常简单,但不幸的是我找不到解决方法。

我想运行一个 def A,它仅从 def B 返回多个值一次。

我写了这段代码:

def A():
x = 1
y = 2
z = 3
return a,b,c

def B():
d = A[0] + A[1]
e = A[2] - A[0]
print d,e

B()

如果我使用这段代码,它将运行四次!

提前致谢。

最佳答案

简单,你的代码有错误,A是一个函数,你应该用A()调用它来获取返回值。相反,您可以像 A[0] 一样使用它,它是不可订阅的,并且您可以在 B 函数中分配一个临时变量,以便您可以重新使用返回的值,更改下面应该可以工作:

In [54]: def A():
...: x = 1
...: y = 2
...: z = 3
...: return x,y,z # I fixed your typo too
...:
...: def B():
...: a = A()
...: d = a[0] + a[1]
...: e = a[2] - a[0]
...: print(d,e)
...:
...: B()

3 2

关于python - 如何仅运行一次具有多个值的 def 并将值使用到另一个 def 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39379735/

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