![](/img/trans.png)
[英]Python - Passing functions to another function where the arguments may be modified
[英]Passing dictionary as argument to a function in python where the arguments are functions themselves
我目前正在使用 Python3 和 plotnine 库。
我正在尝试使用带有字典的 plotnine 作为参数。 这是我正在尝试做的一个简单的工作示例:
import pandas as pd
import plotnine as p9
iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
plot = p9.ggplot(data=iris, mapping=p9.aes(x='petal_width')) +\
p9.geom_density(fill='#6bd1e8', alpha=0.5) +\
p9.theme(axis_title_x = p9.element_text(size = 20),\
axis_text_x = p9.element_text(size=10, angle = 45))
print(plot)
在这里,我想在“p9.theme”函数中使用我的字典,但这些函数参数本身就是函数(“p9.element_text”)。
现在我有一个简单的字典:
theme:
axis_title_x:
size: 20
axis_text_x:
size: 10
angle: 45
现在,如果我执行以下操作,它会部分起作用:
p9.theme(axis_title_x = p9.element_text(**conf['axis_title_x']),\
axis_text_x = p9.element_text(**conf['axis_text_x']))
但我想要类似的东西:
p9.theme(**conf['theme'])
我尝试更改字典的结构,但无法使其正常工作。 有没有人知道如何做到这一点或解决方法?
谢谢
您在字典中也有传递功能。 问题是函数**kwargs
在创建时不能在同一个字典中引用。 所以有两种方法。 有两本词典:
def test(a, b, c=None):
print(a, b, c)
def foo(x):
return f'!{x}'
sub_conf = {
'foo': {'x': 2}
}
conf = {
'test': {'a': 1, 'b': foo(**sub_conf['foo'])}
}
test(**conf['test'])
或者分步创建字典,以便您可以引用现有对象。
conf = {
'foo': {'c': 2}
}
conf['test'] = {'a': 1, 'b': foo(**conf['foo'])}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.