【问题标题】:How to combine 2 functions containing a same subset of arguments with same values into 1 function?如何将包含相同参数子集和相同值的 2 个函数组合成 1 个函数?
【发布时间】:2019-06-07 19:48:26
【问题描述】:

我正在使用 Plotly (Python 3.6) 构建一个图表,它可以是散点图或条形图,具体取决于用户输入。我意识到散点图需要一个额外的参数,我希望尽可能避免定义这两种情况,因为所有其他参数都是相同的。

import plotly.offline as pyo
import plotly.graph_objs as go

散点图:

data=go.Scatter(
x=x, 
y=y, 
mode='lines')

条形图:

data=go.Bar(
x=x, 
y=y)

有没有办法将两者组合成一个函数?

我尝试使用函数来确定要使用哪个函数,但无法弄清楚如何确定是否添加第三个参数(模式)。这是我的尝试:

if input == "Scatter":
   fct = go.Scatter
if input == "Bar":
   fct = go.Bar

data=fct(
x=x,
y=y)

如何添加可选的“模式”?我会梦想这样的事情:

    data=fct(
    x=x,
    y=y,
    if input == "Scatter":
       mode="lines"
   )

【问题讨论】:

  • 你知道怎么用吗,**kwargs?
  • 现在多一点,感谢下面的答案!

标签: python plotly


【解决方案1】:

您可以使用**kwargs 来实现此目的。我的示例将input 替换为user_input

import plotly.offline as pyo
import plotly.graph_objs as go
import numpy as np

N = 1000
x = np.random.randn(N)
y = np.random.randn(N)

user_input = "Bar"

if user_input == "Scatter":
    fct = go.Scatter
    fun_kwargs = {'mode': 'lines'} 
if user_input == "Bar":
    fct = go.Bar
    fun_kwargs = {}

fct(x=x, y=y, **fun_kwargs)

输出:

Bar({
    'x': array([-0.51224629, -0.19486754,  0.04559578, ..., -2.47111604,  0.94998171,
                 1.09732577]),
    'y': array([ 2.0182325 ,  0.05311828,  0.63149072, ...,  0.65456449,  0.73614411,
                -1.02471641])
})

现在使用“Scatter”:

user_input = "Scatter"

if user_input == "Scatter":
    fct = go.Scatter
    fun_kwargs = {'mode': 'lines'} 
if user_input == "Bar":
    fct = go.Bar
    fun_kwargs = {}

fct(x=x, y=y, **fun_kwargs)

输出:

Scatter({
    'mode': 'lines',
    'x': array([ 1.3311512 ,  1.72058406, -1.11571885, ..., -0.66691056, -1.81278558,
                 0.75089731]),
    'y': array([-0.77526413, -0.06880226, -0.45198727, ..., -1.35639219, -0.16597244,
                -0.91315996])
})

【讨论】:

    猜你喜欢
    • 2022-12-25
    • 2020-11-17
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 2017-04-05
    • 2019-05-10
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多