如何从Python中的函数返回多个值?

发布于 2024-07-11 00:30:43 字数 27 浏览 2 评论 0原文

如何从Python中的函数返回多个变量?

How to return more than one variable from a function in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

衣神在巴黎 2024-07-18 00:30:43

您可以用逗号分隔要返回的值:

def get_name():
   # you code
   return first_name, last_name

逗号表示它是一个元组,因此您可以用括号将您的值括起来:

return (first_name, last_name)

然后,当您调用该函数时,您 a) 将所有值作为元组保存到一个变量中,或 b) 分开你的变量名用逗号分隔

name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly

You separate the values you want to return by commas:

def get_name():
   # you code
   return first_name, last_name

The commas indicate it's a tuple, so you could wrap your values by parentheses:

return (first_name, last_name)

Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas

name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly
怪我太投入 2024-07-18 00:30:43

这也是处理结果的代码:

def foo (a):
    x=a
    y=a*2
    return (x,y)

(x,y) = foo(50)

Here is also the code to handle the result:

def foo (a):
    x=a
    y=a*2
    return (x,y)

(x,y) = foo(50)
半暖夏伤 2024-07-18 00:30:43

作为元组返回,例如

def foo (a):
    x=a
    y=a*2
    return (x,y)

Return as a tuple, e.g.

def foo (a):
    x=a
    y=a*2
    return (x,y)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文