gpt4 book ai didi

python - 如何将包含相同参数子集且值相同的 2 个函数合并为 1 个函数?

转载 作者:行者123 更新时间:2023-12-01 07:45:10 25 4
gpt4 key购买 nike

我正在使用 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来实现这一点。我的示例将 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])
})

现在使用“分散”:

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])
})

关于python - 如何将包含相同参数子集且值相同的 2 个函数合并为 1 个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56500457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com