Python中对多个变量执行if-else的更简洁方法

2024-10-03 21:27:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有4个变量需要检查它是真是假。所有的组合将在一起。。4真,3真1假,2真2假,1真3假和全部假。。总的来说,这将产生10++的条件(有点懒于计数)

    if game and owner and platform and is_new and for_sale:
        game_copy = GameCopy.objects.all()
    elif game:
        game_copy = GameCopy.objects.filter(game=game)
    elif platform:
        game_copy = GameCopy.objects.filter(platform=platform)
    elif owner:
        game_copy = GameCopy.objects.filter(user=owner)
    elif is_new:
        game_copy = GameCopy.objects.filter(is_new=is_new)
    elif for_sale:
        game_copy = GameCopy.objects.filter(for_sale=for_sale)
    else:
        game_copy = GameCopy.objects.all()
    return game_copy

我正在寻找一种更精简的方法来解决这种情况。。希望以5到10行结束


Tags: andgamenewforobjectsissaleall
2条回答

您可以将变量更改为一组标志(以唯一整数设置的位)

GAME     = 1 << 0 # 1
OWNER    = 1 << 1 # 2
PLATFORM = 1 << 2 # 4
IS_NEW   = 1 << 3 # 8
FOR_SALE = 1 << 4 # 16

# for instance flags = GAME
# or           flags = OWNER | IS_NEW

# ensures that there is only one flag set and pass it to you filter
if (flags & (flags-1) == 0) and flags != 0: 
    game_copy = GameCopy.objects.filter(flags)

# Otherwise
else: game_copy = GameCopy.objects.all()
return game_copy

您可以将所有真实的内容添加到字典中,然后通过unpacking keyword arguments将它们传递给函数

args = { "game": game, "owner": owner, "platform": platform, "is_new": is_new, "for_sale": for_sale }

# check if all args are truthy
all_args = all(v for v in args.values())

# filter out only the truthy args
filtered_args = {k: v for k, v in args.items() if v}

if all_args or not filtered_args:
    # if all_args is true or filtered_args is empty
    game_copy = GameCopy.objects.all()
else:
    # Unpack filtered_args into filter()
    game_copy = GameCopy.objects.filter(**filtered_args)

相关问题 更多 >