Ignore python multiple return value

2019-01-03 04:24发布

Say I have a Python function that returns multiple values in a tuple:

def func():
    return 1, 2

Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:

x, temp = func()

11条回答
ら.Afraid
2楼-- · 2019-01-03 04:29

Remember, when you return more than one item, you're really returning a tuple. So you can do things like this:

def func():
    return 1, 2

print func()[0] # prints 1
print func()[1] # prints 2
查看更多
我命由我不由天
3楼-- · 2019-01-03 04:33

The best solution probably is to name things instead of returning meaningless tuples. Unless there is some logic behind the order of the returned items.

def func():
    return {'lat':1, 'lng':2}

latitude = func()['lat']
print(latitude)

You could even use namedtuple if you want to add extra information about what you are returning:

from collections import namedtuple 
Coordinates = namedtuple('Coordinates', ['lat', 'lng'])

def func():
    return Coordinates(lat=1, lng=2)

latitude = func().lat
print(latitude)

If the things you return are often together then it may be a good idea to even define a class for it.

查看更多
We Are One
4楼-- · 2019-01-03 04:42

This seems like the best choice to me:

val1, val2, ignored1, ignored2 = some_function()

It's not cryptic or ugly (like the func()[index] method), and clearly states your purpose.

查看更多
趁早两清
5楼-- · 2019-01-03 04:44

One common convention is to use a "_" as a variable name for the elements of the tuple you wish to ignore. For instance:

def f():
    return 1, 2, 3

_, _, x = f()
查看更多
家丑人穷心不美
6楼-- · 2019-01-03 04:45

This is not a direct answer to the question. Rather it answers this question: "How do I choose a specific function output from many possible options?".

If you are able to write the function (ie, it is not in a library you cannot modify), then add an input argument that indicates what you want out of the function. Make it a named argument with a default value so in the "common case" you don't even have to specify it.

    def fancy_function( arg1, arg2, return_type=1 ):
        ret_val = None
        if( 1 == return_type ):
            ret_val = arg1 + arg2
        elif( 2 == return_type ):
            ret_val = [ arg1, arg2, arg1 * arg2 ]
        else:
            ret_val = ( arg1, arg2, arg1 + arg2, arg1 * arg2 ) 
        return( ret_val )

This method gives the function "advanced warning" regarding the desired output. Consequently it can skip unneeded processing and only do the work necessary to get your desired output. Also because Python does dynamic typing, the return type can change. Notice how the example returns a scalar, a list or a tuple... whatever you like!

查看更多
欢心
7楼-- · 2019-01-03 04:45

When you have many output from a function and you don't want to call it multiple times, I think the clearest way for selecting the results would be :

results = fct()
a,b = [results[i] for i in list_of_index]

As a minimum working example, also demonstrating that the function is called only once :

def fct(a):
    b=a*2
    c=a+2
    d=a+b
    e=b*2
    f=a*a
    print("fct called")
    return[a,b,c,d,e,f]

results=fct(3)
> fct called

x,y = [results[i] for i in [1,4]]

And the values are as expected :

results
> [3,6,5,9,12,9]
x
> 6
y
> 12

For convenience, Python list indexes can also be used :

x,y = [results[i] for i in [0,-2]]

Returns : a = 3 and b = 12

查看更多
登录 后发表回答