简体   繁体   English

在python中返回解压列表

[英]Returning unpacked list in python

I'm trying to create a function in python that takes any number of arguments, runs some operations on the arguments and lastly returns the new values.我试图在 python 中创建一个函数,它接受任意数量的参数,对参数运行一些操作,最后返回新值。 Eg:例如:

def foo(*args):
    return *[i ** 2 for i in args] # error: cant use starred expression here

a, b, c, d = foo(2, 15, 17, 21)

instead of "unpacking" the list it just spits out a syntax error.而不是“解包”列表,它只是吐出一个语法错误。 I could technically leave out the "unpacking" all together and just have the user write从技术上讲,我可以将“解包”放在一起,而只需让用户编写

def foo(*args):
    return [i ** 2 for i in args]

a, b, c, d = foo(2, 15, 17, 21) # works

e = foo(82) # e is now a list and not just the value

this works when having multiple arguments but not when I only give one.这在有多个参数时有效,但在我只给出一个时无效。 Is there any way to do this easily without the need of using an if-statement to check the number of inputs given?有没有什么方法可以轻松做到这一点,而无需使用 if 语句来检查给定的输入数量?

You can unpack a one value list, you just need a comma after the one name you're assigning to:您可以解压缩一个值列表,您只需要在您分配给的一个名称后面加一个逗号:

e, = foo(82)

This is the same kind of syntax you need to use when creating a 1-tuple.这与创建 1 元组时需要使用的语法相同。 You need to use (x,) , because (x) is identical to x (the parentheses don't create the tuple, the comma does).您需要使用(x,) ,因为(x)x相同(括号不会创建元组,逗号会)。

def foo(*args):
    return [i ** 2 for i in args]

a, b, c, d = foo(2, 15, 17, 21)

works as intended.按预期工作。 Of course, you must ensure that the returned list has exactly as many items as you have on the left side of the assignment.当然,您必须确保返回的列表中的项目数与分配左侧的项目数完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM