Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

python - How to return multiple values from *args?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...