gpt4 book ai didi

python - 使用变量作为函数名和字符串

转载 作者:行者123 更新时间:2023-12-01 09:11:56 25 4
gpt4 key购买 nike

我有以下代码

import pandas as pd
df = pd.DataFrame(columns=['var1', 'var2','var3'])
df.loc[0] = [0,1,2]

def RS():
x = 123
y = 456
z = 'And some more random shit'
return x+y

def BS():
x = -890
y = (456*1)+90
z = 'And some more random shit'
return x-y

def MyCompute(srt, srt_string):
df[srt_string] = srt()
df['1min' + srt_string] = 1-df[srt_string]

MyCompute(srt=RS, srt_string='RS')
MyCompute(srt=BS, srt_string='BS')

有没有办法避免调用MyCompute函数时出现双RS和双BS?

最佳答案

使用属性__name__:

def MyCompute(srt):
df[srt.__name__] = srt()
df['1min' + srt.__name__] = 1 - df[srt.__name__]

MyCompute(srt=RS)
MyCompute(srt=BS)

关于python - 使用变量作为函数名和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60496894/

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