pythonifelse简化_简化“if…elif..else”条件

这篇博客介绍了如何使用字典来简化 Python 中的条件判断,包括用字典直接调用函数、创建类似 switch...case 的函数以及使用装饰器实现更复杂的逻辑。通过示例展示了如何将条件表达式转换为更易读的形式,并提供了如何在程序中应用这些技术的代码片段。
摘要由CSDN通过智能技术生成

如果能有效地使用“if”、“elif”和“else”也不错。但总的来说,你的问题的答案将取决于个人情况。在

不过,说到这里,一种方法是将您的条件放入dict(正如您在标记中突出显示的那样)。在

以下是几个例子:

作为dict:conditions = {

1: 'One',

2: 'Two',

3: 'Three',

4: 'Four',

5: lambda x: x**2 # Can be substituted with actual functions defined elsewhere.

}

x = 3

if x in conditions.keys():

print(conditions[x])

退货:

^{pr2}$

或者对于函数:x = 5

if x in conditions.keys():

func = conditions[x]

print(func(x))

退货:25

使用类似于switch...case的函数:

为了使其更清楚,并具有类似于switch...case语句的内容,可以执行以下操作:def switch(case):

conditions = {

1: 'One',

2: 'Two',

3: 'Three',

4: 'Four',

5: lambda x: x**2

}

return condition[case] if case in conditions else False

它是这样运行的:>>> print(switch(2))

2

或者对于不存在的项目:>>> print(switch(6))

False

在您的示例中实现:

switch...case函数装饰器(包装器)

为了解决您添加的示例,我们可以执行以下操作:

首先,我们需要一个通用开关/外壳装饰器:def switch_case(switch):

def switcher(func):

def case(case):

return switch[case](case) if case in switch else None

return case

return switcher

然后,我们需要一本关于我们的条件的字典,如您的示例所示:# Define the conditions in a dict.

conditions = {

'd': lambda x: True if 'd' else False, # You can say: True if 'a' or 'b' else False

'c': lambda x: True if 'c' else False

}

现在,我们根据您的条件创建一个装饰开关盒函数:@switch_case(conditions)

def my_conditions(case):

return case

然后我们指定元素,或者从文件、数据库或任何东西读取它们:# Elements to be tested as string.

# It can be any flattened (not nested) iterable (str, tuple, list, numpy.array, etc.)

myDict = {'a': ['b', 'c'], 'b': ['c', 'd']}

elements = sum(myDict.values(), []) # Returns a flattened lists of values.

根据条件计算元素(生成器对象)。在verdicts = map(my_conditions, elements)

将元素与相应的计算结果(生成器对象)匹配。在status = zip(elements, verdicts)

现在我们可以积极地调节输出(丢弃Nonevlue)并创建一个dict,其中键是元素,值是它们的条件状态。在passed = {key+'flag': val for key, val in status if val is not None}

print(passed)

# output: {'cflag': True, 'dflag': True}

作为变量添加到命名空间

此时,您可以按原样使用dict;但是,如果您坚持要将dict添加到名称空间中,下面是方法:# Rename values and add them to the name space.

locals().update(passed)

试验

最后,让我们测试并确保这些值存在于本地命名空间中(请注意,我们之前没有实现这些名称中的任何一个)。因此,如果条件返回序列中特定字符的True值,则会创建一个变量:>>> print(dflag) # We had 'd' in `myDict` values.

True

在另一个had中,如果条件返回None,则命名空间中没有值。在>>> print(aflag) # We didn't have 'a' in `myDict` values.

---------------------------------------------------------------------------

NameError Traceback (most recent call last)

in ()

24

---> 25 print(aflag)

NameError: name 'aflag' is not defined

注意:在现有结构下,如果条件返回False,则在命名空间中创建一个变量,并为其赋值False。在

希望这有帮助。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值