How to return multiple values from *args?

99封情书 提交于 2019-12-30 08:29:08

问题


I have a hello function and it takes n arguments (see below code).

def hello(*args):
  # return values

I want to return multiple values from *args. How to do it? For example:

d, e, f = hello(a, b, c)

SOLUTION:

def hello(*args):
  values = {} # values
  rst = [] # result
  for arg in args:
    rst.append(values[arg])
  return rst

a, b, c = hello('d', 'e', f)
a, b = hello('d', 'f')

Just return list. :) :D


回答1:


So, you want to return a new tuple with the same length as args (i.e. len(args)), and whose values are computed from args[0], args[1], etc. Note that you can't modify 'args' directly, e.g. you can't assign args[0] = xxx, that's illegal and will raise a TypeError: 'tuple' object does not support item assignment. What You need to do then is return a new tuple whose length is the same as len(args). For example, if you want your function to add one to every argument, you can do it like this:

def plus_one(*args):
    return tuple(arg + 1 for arg in args)

Or in a more verbose way:

def plus_one(*args):
    result = []
    for arg in args: result.append(arg + 1)
    return tuple(result)

Then, doing :

d, e, f = plus_one(1, 2, 3)

will return a 3-element tuple whose values are 2, 3 and 4.

The function works with any number of arguments.




回答2:


Just return a tuple:

def hello(*args):
    return 1, 2, 3

...or...

    return (1, 2, 3)



回答3:


args is a list. if you return a sequence (list, tuple), Python will try to iterate and assign to your d, e, f variables. so following code is ok.

def hello(*args):
   return args

d, e,  f = hello(1,2,3)

As long as you have, the right number of values in the *args list. It will be assigned to your variables. If not, il will raise a ValueError exception.

d, e, f = hello(1, 2) #raise ValueError

I hope ith helps




回答4:


Just return them. For instance, if you want to return the parameters unmodified, do this:

def hello(*args):
    return args

If you want to return something else, return that instead:

def hello(*args):
    # ...
    # Compute d, e and f
    # ...
    return d, e, f


来源:https://stackoverflow.com/questions/8381739/how-to-return-multiple-values-from-args

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!