Python 处理变量设置比处理多个if语句更简洁的解决方案

Python 处理变量设置比处理多个if语句更简洁的解决方案,python,Python,我有一组if语句,它们根据我尝试执行的操作类型设置变量 if reverse_relationship and not get_all_links: traversal_function = 'reverse' annotation_function = 'forward' elif reverse_relationship and get_all_links: traversal_function = 'all_reverse' annotation_funct

我有一组if语句,它们根据我尝试执行的操作类型设置变量

if reverse_relationship and not get_all_links:
    traversal_function = 'reverse'
    annotation_function = 'forward'
elif reverse_relationship and get_all_links:
    traversal_function = 'all_reverse'
    annotation_function = 'all_forward'
    item_id_query = 'reverse'
elif get_all_links:
    traversal_function = 'all_forward'
    annotation_function = 'all_reverse'
    item_id_query = 'forward'
else:
    traversal_function = 'forward'
    annotation_function = 'reverse'
但我觉得必须有一种更简单的方法来做到这一点,因为上面的内容很难阅读。

类似于:

if reverse_relationship:
    if get_all_links:
        traversal_function = 'all_reverse'
        annotation_function = 'all_forward'
        item_id_query = 'reverse'
    else:
        traversal_function = 'reverse'
        annotation_function = 'forward'
else:
    if get_all_links:
        traversal_function = 'all_forward'
        annotation_function = 'all_reverse'
        item_id_query = 'forward'
    else:
        traversal_function = 'forward'
        annotation_function = 'reverse'
还请注意,您可能未定义
项目\u id\u查询

编辑: 更紧凑的版本

item_id_query = 'reverse' if reverse_relationship else 'forward'
traversal_function = item_id_query
annotation_function = 'forward' if reverse_relationship else 'reverse'
if get_all_links:
    traversal_function = f'all_{traversal_function}'
    annotation_function = f'all_{annotation_function}'

可以使用字典更简洁地执行此操作,其中键是元组,包含if语句的布尔输入,值是生成的三个字符串:

map = {
    (True, False): ('reverse', 'forward', None),
    (True, True): ('all_reverse', 'all_forward', 'reverse'),
    (False, True): ('all_forward', 'all_reverse', 'forward'),
    (False, False): ('forward', 'reverse', None),
}

traversal_function, annotation_function, item_id_query = map[(reverse_relationship, get_all_links)]
@konserw的第二个答案是另一种方法,如果您想利用这样一个事实,即结果字符串是以基于输入的逻辑方式构建的。请注意,它们提供的解决方案会导致
item\u query\u id
在所有情况下都具有非None值,这与您的代码不匹配。要获得与您的解决方案相同的结果,只需更改以查看始终定义了
get\u all\u links
,但为
None
。对于您未在代码中设置的情况,您可以更改其答案:

item_id_query = None
traversal_function = 'reverse' if reverse_relationship else 'forward'
annotation_function = 'forward' if reverse_relationship else 'reverse'
if get_all_links:
    item_id_query = traversal_function
    traversal_function = f'all_{traversal_function}'
    annotation_function = f'all_{annotation_function}'

要使此代码与您的
if
语句完全相同,只需删除此代码的第一行。我不建议这样做,因为我认为您希望在所有情况下都定义
item\u id\u query

这似乎是一个简单的解决方案。根据您分配的特定值模式,可以简化一点:在
反向关系上设置
if
/
else
,将两个变量按一定顺序设置为“正向”/“反向”,然后是一个
if get\u all\u链接:
,它只是在这些值前面添加“all\u”。这是一个XY问题。下一步你将如何处理这些字符串?我认为这是代码库更大问题的一部分。我的猜测是,您有这些遍历函数的实现。在这种情况下,责任链可能适用。太棒了,谢谢!