我有以下方法。我试图将多个变量传递给第一种方法,然后将它们重命名,然后再传递给第二种方法。
def method2(**kwargs):
# Print kwargs
for key in kwargs:
print(key, kwargs[key])
def method1(**kwargs):
# Need to rename kwargs to pass in to method2 below
# Keys are method1 kwargs variables and values are method 2 kwargs variables
rename_dict = {'Val1': 'val_1', 'Val2': 'val_2', 'Val3': 'val_3'}
new_kwargs = {}
# The kwargs passed in method 1 need to their values to be set to the
# corresponding variables in the rename_dict before they are pass in method 2
method2(**new_kwargs)
method1(Val1 = 5, Val2 = 6)
# Output desired
val_1 5
val_2 6
答案 0 :(得分:1)
您可以通过dict理解更简洁地编写它:
new_kwargs = {rename_dict[key]: value for key, value in kwargs.items()}
答案 1 :(得分:1)
要重命名dict键,可以使用以下命令:
Loading execution data file jacoco.exec
Analyzed bundle 'xxx-api' with 884 classes
[WARNING] Rule violated for bundle xxx-api: classes missed count is 36, but expected maximum is 35
此外,您可以使用new_kwargs = {rename_dict[key]:value in key,value for kwargs.items()}
在python中迭代字典,该字典返回元组(键,值)的列表,并且可以直接在循环中将其解压缩:
items()
答案 2 :(得分:0)
我能够通过在第一种方法中添加for循环来做到这一点
def method2(**kwargs):
# Print kwargs
for key in kwargs:
print(key, kwargs[key])
def method1(**kwargs):
# Need to rename kwargs to pass in to method2 below
# Keys are method1 kwargs variables and values are method 2 kwargs variables
rename_dict = {'Val1': 'val_1', 'Val2': 'val_2', 'Val3': 'val_3'}
new_kwargs = {}
for key in kwargs:
new_kwargs[rename_dict[key]] = kwargs[key]
print(new_kwargs)
# The kwargs passed in method 1 need to their values to be set to the
# corresponding variables in the rename_dict before they are pass in method 2
method2(**new_kwargs)
method1(Val1 = 5, Val2 = 6)
# Output
{'val_1': 5, 'val_2': 6}
val_1 5
val_2 6
我没有意识到您可以在python方法中将变量名作为字符串传递。我希望我能帮助尝试做同一件事的人!