如何从* args返回多个值? [英] How to return multiple values from *args?

查看:237
本文介绍了如何从* args返回多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

   def hello(* args):
#返回值

I想要从 * args 返回多个值。怎么做?例如:

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

解决方案:

 <$ c $ args:
values = {}#values
rst = []#结果
用于参数arg:
rst.append(values [arg ])
return rst

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

只需返回列表。 :):D

解决方案

所以,你想返回一个长度与args相同的新元组(即len(args) ),其值从args [0],args [1]等计算。
请注意,您不能直接修改'args',例如你不能指定args [0] = xxx,这是非法的,会引发TypeError:'元组'对象不支持项目分配。
然后,你需要做的是返回一个长度与len(args)相同的新元组。
例如,如果您希望函数为每个参数添加一个,您可以这样做:

  def plus_one(* args):
返回元组(参数中的arg + 1)

或以更详细的方式:

  def plus_one(* args):
result = []
为arg中的参数:result.append(arg + 1)
返回元组(结果)



<然后,做:

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

code>

将返回值为2,3和4的3元组元素。



该函数可以处理任意数量的参数。


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

解决方案

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.

这篇关于如何从* args返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆