Python返回未打包字典



我想根据某些条件返回一个未打包的字典:

def process(batch, cond):
if(cond):
return **batch
else
return batch
input = process(batch, cond)
output = model(input)

然而,我得到一个SyntaxError: invalid syntax,因为return **batch线。

你不能。您需要将解包逻辑提取到process之外:

def process(batch):
return batch
input = process(batch)
if cond:
output = model(**input)
else:
output = model(input)

如果你真的需要process,也传递model给它:

def process(batch, model, cond):
input = process(batch)
if cond:
return model(**input)
return model(input)
output = process(batch, model, cond)

如果我理解正确的话,你可以像这样实现你想要的:

def process(batch, cond):
if(cond):
kwargs = batch
else:
kwargs = {'a': batch}
return kwargs
def model(a=0, b=0, c=0):
print(a + b + c)
batch = {'a': 100, 'b': 101, 'c': 102}
cond = True
kwargs = process(batch, cond)
model(**kwargs)
# Output: 303
batch = 100
cond = False
kwargs = process(batch, cond)
model(**kwargs)
# Output: 100

相关内容

  • 没有找到相关文章

最新更新