简体   繁体   English

如何在python中避免使用过多的if - else块

[英]how to avoid too many if - else blocks in python

I wrote a class that check 4 parameters in input and shows a list a result in output. 我写了一个类,检查输入中的4个参数,并在输出中显示结果列表。 Only one of this parameter is required, therefore i have 7 if - else nested blocks. 只需要此参数中的一个,因此我有7个if - else嵌套块。 I want to specify that the condition as stated works properly. 我想指定所述条件正常工作。

I was wandering if there was a smarter way to write this: 如果有一个更聪明的方式来写这个,我在徘徊:

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})

Internally, the keyword arguments you're passing to the function are just a dict . 在内部,您传递给函数的关键字参数只是一个dict So build it yourself and pass it to the function using the **name syntax: 所以自己构建它并使用**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})

使用关键字args构建一个dict,用于调用filter() ,然后使用**kwargs语法传递它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM