如何允许给定字符串中的每个允许字符触发 if 语句

How to allow each allowed character in given string to trigger if-statement

我在这里搜索了一会儿,似乎没有什么能真正概括我的实际问题,因为我希望我给定的字符串(如果它的字符符合我的条件)导致不同的 if 语句。我的代码的目的是让每个字母代表我的字符串的旋转。

示例部分['rotate'] = 'Ff'

allowed = ['F', 'f', 'R', 'r', 'B', 'b', 'L', 'l', 'U', 'u', 'D', 'd']

def rotated(parms):
    result = {}
    if ('cube' not in parms):
        result['status'] = 'error: cube is missing!'
    cube = list(parms['cube'])
    if ('rotate' not in parms or parms['rotate'] == ''):
        return rotateF(cube)
    if (parms['rotate'] == 'F'):
        return rotateF(cube)
    if (parms['rotate'] == 'f'):
        return rotatef(cube)
    if (parms['rotate'] != allowed):
        result['status'] = 'error: invalid rotation'
return result

def rotateF(cube):
    rotatedCube = list(cube)
    .....
    rotatedCube = ''.join(rotatedCube)
    return rotatedCube
def rotatef(cube):
    rotatedCube = list(cube)
    ......
    rotatedCube = ''.join(rotatedCube)
    return rotatedCube

所以目前,我得到的 return 是 'rotate' = 'Ff' :

{'status': 'error: invalid rotation'}

我的假设是因为目前,我的代码一次只允许一个字符,而我只是想确保这些是唯一允许的字符,而不是每个字符串一个。

您的旋转函数的编写方式是与特定字符串进行比较,但您似乎提供了旋转列表(在 python 中,字符串是字符列表)。尝试引入另一个辅助函数,将 rotated 拆分为 do_single_rotationdo_all_rotations 之类的东西(我遗漏了一些错误处理和诸如此类的东西,因为我不确定你到底是什么目标是 return)

default_rotate_str = 'F'

def do_all_rotations(parms):
    rotate_str = parms.get('rotate', default_rotate_str)
    cube = list(parms['cube'])
    for rotate_command in rotate_str:
        cube = do_single_rotation(cube, rotate_command)
    return cube

def do_single_rotation(cube, rotate_command):
    if rotate_command == 'F':
        return rotate_F(cube)
    if rotate_command == 'f';
        return rotate_f(cube)
    # .... continue
    if rotate_command == 'D':
        rotate_d(cube)
    raise ValueError("unrecognized rotate command")