[英]What is an elegant way to select all non-None elements from parameters and place them in a python dictionary?
def function(varone=None, vartwo=None, varthree=None):
values = {}
if var1 is not None:
values['var1'] = varone
if var2 is not None:
values['var2'] = vartwo
if var3 is not None:
values['var3'] = varthree
if not values:
raise Exception("No values provided")
Can someone suggest a more elegant, pythonic way to accomplish taking placing non-null named variables and placing them in a dictionary? 有人可以建议一个更优雅,pythonic的方法来完成非空命名变量并将它们放在字典中吗? I do not want the values to be passed in as a dictionary.
我不希望值作为字典传入。 The key names of "values" are important and must be as they are.
“价值观”的关键名称很重要,必须保持原样。 The value of "varone" must go into var1, "vartwo" must go into var2 and so on;
“varone”的值必须进入var1,“vartwo”必须进入var2,依此类推; Thanks.
谢谢。
You could use kwargs
: 你可以使用
kwargs
:
def function(*args, **kwargs):
values = {}
for k in kwargs:
if kwargs[k] is not None:
values[k] = kwargs[k]
if not values:
raise Exception("No values provided")
return values
>>> function(varone=None, vartwo="fish", varthree=None)
{'vartwo': 'fish'}
With this syntax, Python removes the need to explicitly specify any argument list, and allows functions to handle any old keyword arguments they want. 使用这种语法,Python不需要显式指定任何参数列表,并允许函数处理他们想要的任何旧关键字参数。
If you're specifically looking for keys var1
etc instead of varone
you just modify the function call: 如果您专门寻找密钥
var1
等而不是varone
您只需修改函数调用:
>>> function(var1=None, var2="fish", var3=None)
{'var2': 'fish'}
If you want to be REALLY slick, you can use list comprehensions: 如果你想真正光滑,你可以使用列表推导:
def function(**kwargs):
values = dict([i for i in kwargs.iteritems() if i[1] != None])
if not values:
raise Exception("foo")
return values
Again, you'll have to alter your parameter names to be consistent with your output keys. 同样,您必须更改参数名称以与输出键保持一致。
Use **kwargs
. 使用
**kwargs
。 Example: 例:
def function(**kwargs):
if not kwargs:
raise Exception("No values provided")
for k, v in kwargs.items():
print("%s: %r") % (k, v)
If you really are going to call function
with None
arguments, you can strip them out: 如果你真的打算使用
None
参数调用function
,你可以将它们删除:
def function(**kwargs):
for k, v in kwargs.items():
if v is None:
del kwargs[k]
if not kwargs:
raise Exception("No values provided")
for k, v in kwargs.items():
print("%s: %r") % (k, v)
Obviously you could call the dict values
instead, but kwargs
is the conventional name, and will make your code more intelligible to other people. 显然你可以调用dict
values
,但kwargs
是常规名称,并且会使你的代码对其他人更容易理解。
Well, you can pass all those values inside a keyword argument
: - 好吧,你可以在
keyword argument
传递所有这些值: -
def function(*nkwargs, **kwargs):
values = {}
for k in kwargs:
if kwargs[k] is not None:
values[k] = kwargs[k]
if not values:
raise Exception("No values")
print values
try:
function()
except Exception, e:
print e
function(varOne=123, varTwo=None)
function(varOne=123, varTwo=234)
OUTPUT : - 输出 : -
No values
{'varOne': 123}
{'varOne': 123, 'varTwo': 234}
Call your function as usual, but accept as **kwargs
. 像往常一样调用你的函数,但接受
**kwargs
。 Then filter them: 然后过滤它们:
def fn(**kwargs):
items = {'var%s' % i: v for i, (k, v) in enumerate(items)}
fn(a=1, b=2, c=3)
if you need a specific set of names, then make a dict of names: 如果你需要一组特定的名字,那就制作一个名字的词典:
names = dict(zip('varOne varTwo varThree'.split(), range(1, 4)))
walk over this dict and check if the var is in kwargs: 走过这个字典并检查var是否在kwargs中:
items = {'var%s' % k: kwargs[v] for k, v in names.items() if v in kwargs}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.