gpt4 book ai didi

python - 如何避免太多 if - else block 在 python 中

转载 作者:太空宇宙 更新时间:2023-11-03 13:45:50 25 4
gpt4 key购买 nike

我编写了一个检查输入中的 4 个参数并在输出中显示结果列表的类。此参数中只有一个是必需的,因此我有 7 个 if - else 嵌套 block 。我想指定所述条件是否正常工作。

我在徘徊是否有更聪明的方式来写这个:

if cd['subject'] is None:
if cd['school'] == '':
if cd['price']:
files = File.objects.filter(name__contains=cd['name'], price = '0.0')
else:
files = File.objects.filter(name__contains=cd['name'])
else:
if cd['price']:
files = File.objects.filter(name__contains=cd['name'], school = cd['school'], price = '0.0')
else:
files = File.objects.filter(name__contains=cd['name'], school = cd['school'])
else:
if cd['school'] == '':
if cd['price']:
files = File.objects.filter(name__contains=cd['name'], subject = cd['subject'], price = '0.0')
else:
files = File.objects.filter(name__contains=cd['name'], subject = cd['subject'])
else:
if cd['price']:
files = File.objects.filter(name__contains=cd['name'], school = cd['school'], subject = cd['subject'], price = '0.0')
else:
files = File.objects.filter(name__contains=cd['name'], school = cd['school'], subject = cd['subject'])
return render(request, 'search.html', {'files': files, 'request': request})

最佳答案

在内部,您传递给函数的关键字参数只是一个dict。所以自己构建它并使用 **name 语法将它传递给函数:

args = {}

args['name__contains'] = cd['name']

if cd['subject'] is not None:
args['subject'] = cd['subject']
if cd['school'] != '':
args['school'] = cd['school']
if cd['price']:
args['price'] = cd['price']

files = File.objects.filter(**args)
return render(request, 'search.html', {'files': files, 'request': request})

关于python - 如何避免太多 if - else block 在 python 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20751124/

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