[英]How to use a string as a function parameter in Python and have variable number of parameters
I have a function called filter that accepts a number of parameters in the format name=value. 我有一个名为filter的函数,该函数接受name = value格式的许多参数。 I have 2 lists: names and values (let's call them x and y), I need to be able to pass these into the function.
我有2个列表:名称和值(我们将它们称为x和y),我需要能够将它们传递给函数。
When I just pass in the string as in the below example, it gives me an error: 如下面的示例所示,当我仅传递字符串时,它给我一个错误:
x = ['t', 't2']
y = [w, w2]
filter(x[0]=y[0], x[1]=y[1])
SyntaxError: keyword can't be an expression SyntaxError:关键字不能是表达式
I would also need to be able to pass in an arbitrary amount, for the size of the lists. 对于列表的大小,我还需要能够任意传递。 How can I go about making this work?
我该如何进行这项工作?
Use **kwargs
: 使用
**kwargs
:
kwargs = {x[0]: y[0], x[1]: y[1]}
filter(**kwargs)
You probably don't want to have a function called filter as that will overwrite the built-in python filter function. 您可能不想使用一个名为filter的函数,因为它将覆盖内置的python filter函数。 But otherwise read up on using *args and **kwargs , sounds like what you need.
但是,否则请继续阅读* args和** kwargs ,听起来像您所需要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.