从连接字符串名称调用 Python 函数名称

Wes*_*esZ 1 python function

我想通过连接“字符串”+变量+“字符串”创建一个 def 函数名称并调用该 def 函数。

为了简单起见,我目前正在使用这个压缩版本的代码来类似地完成任务,并且我想最小化函数 do_update(a) 的硬代码内容:

ROTATE = '90'

ROT20 = [
[0, 0, 0, 0, 0, 0, 0, 0],
[126, 129, 153, 189, 129, 165, 129, 126],
[126, 255, 231, 195, 255, 219, 255, 126],
[0, 8, 28, 62, 127, 127, 127, 54],
[0, 8, 28, 62, 127, 62, 28, 8],
[62, 28, 62, 127, 127, 28, 62, 28],
[62, 28, 62, 127, 62, 28, 8, 8],
[0, 0, 24, 60, 60, 24, 0, 0],
];

def updatevalues90(a):
  b = []
  for i in range(8):
    for j in range(8):
      b[i] += a[j] + i
  return b

def do_update(a):  
  if ROTATE == '90':
    ROT = [updatevalues90(char) for char in a]
  elif ROTATE == '180':  
    ROT = [updatevalues180(char) for char in a]
  elif ROTATE == '270':
    ROT = [updatevalues270(char) for char in a]

do_update(ROT20)
Run Code Online (Sandbox Code Playgroud)

我尝试过的所有方法都导致无效语法或 ROT 填充了我想要的字符串名称。

我想对 updatevalues90(char) 进行函数调用,而不是需要对其进行硬编码,我想将其更改为:

ROT = ["updatevalues" + ROTATE + "(char)" for char in a]

这样,ROTATE 中的任何值都将成为函数调用的一部分,即函数名称。

我的问题是在 Python 中如何将字符串和变量名连接成可用的函数名?

我认为 eval,但我无法让语法为我工作。也许 Python 中有更简单的东西可以工作?

che*_*ner 5

将您的函数存储在dict

updaters = {
  '90': updatevalues90,
  '180': updatevalues180,
  '270': updatevalues270
}

def do_update(a):
    ROT = [updaters[ROTATE](char) for char in a]
    # return ROT   ?
Run Code Online (Sandbox Code Playgroud)