[英]Passing List to Function in place of Many Arguments
First, I apologize if a similar question has been addressed. 首先,对于类似的问题已经解决,我深表歉意。 I looked but had no luck (which could be from me not knowing how to properly search for this question.) In it's simplest form, suppose we have the following:
我看了一下,但是没有运气(可能是由于我不知道如何正确搜索此问题。)以最简单的形式,假设我们有以下内容:
def func(x, a, b):
return a*x + b*b
c = [2, 3]
How would you use the function like, func(x, c)
? 您将如何使用
func(x, c)
类的func(x, c)
? Specifically, rather than writing out an entire array's elements as arguments to a function, how do you cleanly in place of the arguments reference an array? 具体而言,与其将整个数组的元素写出作为函数的参数,不如将参数完全引用到数组中,您该如何干净地呢?
You can use extended iterable unpacking operator . 您可以使用扩展的可迭代拆包运算符 。
def func(x, a, b):
return a*x + b*b
c = [2, 3]
func(x,*c)
The answer might be: Packing 答案可能是:包装
When we don't know how many arguments need to be passed to a python function, we can use Packing to pack all arguments in a tuple. 当我们不知道需要向python函数传递多少个参数时,可以使用Packing将所有参数打包到一个元组中。
# A Python program to demonstrate use
# of packing
# This function uses packing to sum
# unknown number of arguments
def mySum(*args):
sum = 0
for i in range(0, len(args)):
sum = sum + args[i]
return sum
# Driver code
print(mySum(1, 2, 3, 4, 5))
print(mySum(10, 20))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.