簡體   English   中英

將字典作為參數傳遞給python中的函數,其中參數是函數本身

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM