Python函数返回 [英] Python Function Return
问题描述
如果我想从Python中的一个函数返回更多的一个变量,我一直在做以下工作:
def foo ():
firstName ='Bob'
lastName ='Jones'
return [firstName,lastName]
然后,如果我只想找到第一个名字,我会这样做的。
[firstName ,dummy] = foo()
然而,假设我最初有这个函数
def fooInitial():
firstName ='Bob'
返回firstName
我从代码的很多部分调用了这个,如果我想添加 lastName
作为另一个输出我一直在做的方式,我将不得不改变我的代码中的任何其他地方调用它。
有没有办法做类似于Matlab的地方, a = foo()
给我名字(不是列表中的第一个也不是最后一个)并且 [a,b] = foo()
给了我第一个也是最后一个?
不,没有。你最好改变所有调用 fooInitial()
的代码,或者添加一个返回两个参数的不同的方法
$ b $ $ $ $ $ $ c $ def $ in $($):
$> fooInitial()使用该方法:
返回first_name,last_name
$ b def fooInitial():
返回barInitial()[0]
请注意,您可以仅返回一个元组而不是列表;元组只需要逗号来定义,所以语法更轻(不需要方括号)。解包返回值时可以这样做:
first_name,last_name = barInitial()
If I want to return more that one variable from a function in Python I have been doing the following:
def foo():
firstName = 'Bob'
lastName = 'Jones'
return [firstName, lastName]
Then if I wanted to find only the first name I would do this
[firstName, dummy] = foo()
However, say I initially had the function
def fooInitial():
firstName = 'Bob'
return firstName
and I called this from many parts of my code, if I wanted to add the lastName
as another output the way I have been doing, I would have to change everywhere else in my code that was calling it.
Is there a way to do something similar to Matlab where calling a = foo()
gives me the first name (not the first and last in a list) and [a,b]=foo()
gives me the first and last?
No, there isn't. You are better of either changing all the code calling fooInitial()
, or by adding a different method that returns the two parameters and have fooInitial()
use that method:
def barInitial():
first_name, last_name = 'Bob', 'Jones'
return first_name, last_name
def fooInitial():
return barInitial()[0]
Note that you can just return a tuple instead of a list too; tuples only require a comma to define so the syntax is lighter (no need for square brackets). You can do the same when unpacking the returned value:
first_name, last_name = barInitial()
这篇关于Python函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!