gpt4 book ai didi

python - 避免多个 IF 以确保 Mccabe 复杂性

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:39:44 25 4
gpt4 key购买 nike

我想问你对以下场景的不同看法:假设我们有几个列表,应该对那些不为空的列表执行一些操作:

if l1 or l2 or l3 or l4 or l5 or l6 or l7 or l8 or l9:

print 'we have to do something in one or more lists'

if l1:
print 'l1'
f1()

if l2:
print 'l2'
f2()

if l3:
print 'l3'
f3()

if l4:
print 'l4'
f4()

if l5:
print 'l5'
f5()

if l6:
print 'l6'
f6()

if l7:
print 'l7'
f7()

if l8:
print 'l8'
f8()

if l9:
print 'l9'
f9()

代码本身简单易懂,但这会引发 (12) 的 Mccabe 复杂度值。要降低此值,您将如何处理它?我很乐意听听您的想法。

提前谢谢你。

更新:

准确地想象一下这个具体情况。你怎么能接近它?:

    if a:
A = True

if b:
B = True

if c:
C = True

if d:
D = "D"

if e:
E = "E"

if f:
F = "F"

我认为,在这种情况下,创建 6 个不同的函数效率不高而且python...

最佳答案

使用列表列表和函数列表

def f1(l1):
# do whatever is required to the l1 list

def f2(l2):
# similarly

# and similarly for f3 .. f9

...

lofl = [ l1, l2, l3, l4, l5, l6, l7, l8, l9 ]
loff = [ f1, f2, f3, f4, f5, f6, f7, f8, f9 ]

for f, l in zip( loff, lofl):
if l: # if the functions f cannot themselves safely do nothing for a falsy argument
f( l)

希望所需的函数数量少于九个(在本例中)。您还可以轻松地向函数传递一个参数,这样一个函数就可以是通用的,并告诉它在调用时要执行什么变体操作

for f, l, p in zip( loff, lofl, lofp): # or, zip( loff, lofl, list(range(9)) )
f(l, p)

或者甚至向函数传递任意一组关键字参数

lofargs=[ { 'foo':1, 'bar':'Monty' }, # kwargs for f1
{ 'foo':2, 'bar':'Python'},
{ 'foo':3 },
{}, # no kwargs at all for f4,
...
]


for f, l, k in zip( loff, lofl, lofargs):
f( l, **k )

几年后重温这一点,我现在全力以赴地采用目录方法:

callstruct = [
{ 'func':f1, 'arg':l1, 'foo':1, 'bar':'Monty' },
{ 'func':f2, 'arg':l2, 'foo':2, 'bar':'Python'},
{ 'func':f3, 'arg':l3, 'foo':3 },
{ 'func':f4, 'arg':l4}, # no kwargs at all for f4,
...
]

for d in callstruct:
func = d.pop('func')
arg = d.pop('arg')
func( arg, **d)

如果有任何外部循环,请注意 .pop 会改变 callstruct 中的字典,因此您可能希望从 dd = d.copy 开始() 并在 dd 上工作。

不知道为什么我现在有这种感觉。也许太多的 JavaScript 曝光?我经常在我最近的代码中找到这样的单行代码。比许多 if

更具可读性和可扩展性
 x = {'foo':1, 'bar':2, 'baz':3}.get(choice, DEFAULT) # or ERROR, or catch KeyError

关于python - 避免多个 IF 以确保 Mccabe 复杂性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52850003/

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