简体   繁体   English

如何使多个 if 语句更加“pythonic”和简洁?

[英]How to make a multiple if statements more "pythonic" and condensed?

I am writing a piece of software that checks the input to a function before passing it to a database.我正在编写一个软件,在将输入传递给数据库之前检查 function 的输入。 To do this I need to check the type of data before I send it.为此,我需要在发送数据之前检查数据类型。 Right now I am using 5 different if/else statements.现在我正在使用 5 种不同的 if/else 语句。 How can I condense this and make it easier to read?我怎样才能浓缩它并使它更容易阅读? Thank You!谢谢你!

def addUser(USERNAME, PASSWORD, PHONE, CARRIER, SERVER):
    good = True
    if type(USERNAME) == str and good:
        good = True
    else:
        good = False
    if type(PASSWORD) == str and good:
        good = True
    else:
        good = False
    if type(PHONE) == int and good:
        good = True
    else:
        good = False
    if type(CARRIER) == str and good:
        good = True
    else:
        good = False
    if type(SERVER) == str and good: 
        good = True
    else:
        good = False      

Combine all the conditions into one:将所有条件合二为一:

good = type(USERNAME) == str and type(PASSWORD) == str and type(PHONE) == int AND type(CARRIER) == str and type(SERVER) == str

BTW, you generally shouldn't use int for phone numbers.顺便说一句,您通常不应该将int用于电话号码。 Even though we call them phone numbers we don't perform any numeric operations on them.即使我们称它们为电话号码,我们也不会对它们执行任何数字操作。 And putting a phone number in an int variable will lose leading zeroes.并且将电话号码放入int变量中会丢失前导零。

You could loop over all of them.你可以遍历所有这些。 eg:例如:

def check_parameters(params: list):
    for parameter in params:
        if not isinstance(parameter,str):
            return False
    return True


def addUser(USERNAME, PASSWORD, PHONE, CARRIER, SERVER):
    good = check_parameters([USERNAME, PASSWORD, PHONE, CARRIER, SERVER])

Note isinstance(Your_string, str) is preferred to `type() == '注意 isinstance(Your_string, str) 优于 `type() == '

All the conditions must be True.所有条件都必须为真。 The most pythonic way would be two create two lists — one with the fields and one with their respective types, then compare the two lists and check if all conditions are True.最pythonic的方法是两个创建两个列表——一个带有字段,一个带有各自的类型,然后比较两个列表并检查所有条件是否为真。 This way you can add any number of fields by appending the fields and types lists.这样,您可以通过附加fieldstypes列表来添加任意数量的字段。 This way you will also avoid one very long statement with multiple conditions and the and operator between them这样,您还可以避免一个很长的语句,其中包含多个条件以及它们之间的and运算符

fields = [USERNAME, PASSWORD, PHONE, CARRIER, SERVER] # append new field if you want
types = [str, str, int, str, str] # append type of new field if you want
good = all(type(field)==types[i] for i, field in enumerate(fields))

To build on JeffUK's answer, you should also raise an error to tell the user which one is wrong if one fails the type test ( "Errors should never pass silently." ):为了建立 JeffUK 的答案,您还应该提出一个错误,告诉用户如果一个未通过类型测试,哪个是错误的( “错误永远不应该默默地通过。” ):

def check_parameters(params: list):
    for i, parameter in enumerate(params):
        if not isinstance(parameter,str):
            raise ValueError(f'{parameter} in position {i} is {type(parameter)}, not string.')
    return True

You then can wrap your function call in a try block to catch the error.然后,您可以将 function 调用包装在 try 块中以捕获错误。

def addUser(USERNAME, PASSWORD, PHONE, CARRIER, SERVER):
    try:        
        good = check_parameters([USERNAME, PASSWORD, PHONE, CARRIER, SERVER])
    except ValueError as e:
        print(e)

If you are using Python 3.10, a match-case statement might work well for your particular code.如果您使用的是 Python 3.10,则match-case语句可能适用于您的特定代码。

You could also try putting the valid input types into a dictionary, which could condense the code by eliminating the else statements.您还可以尝试将有效的输入类型放入字典中,这样可以通过消除 else 语句来压缩代码。 eg,例如,

data_type_check = {'username': str, 'password': str, 'phone': int,
                   'carrier': str, 'server': str}

for var, key in zip([USERNAME, PASSWORD, PHONE, CARRIER, SERVER], 
                    ['username', 'password', 'phone', 'carrier', 'server']):

    good = type(var) == data_type_check[key]

    if not good:
        break
    

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

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