在python中使用多个if-elif-else语句时,如何重构该函数以降低其认知复杂性问题



我的问题是,如果下面的代码中存在elif-else条件,如何重构。

由于新的实现,这里的代码已经更改。这里的V、X、Y是数字。此代码用于生成随机字符串。

def get_uid(type, key):
if type == 'orange_fruit':
if key == 'juice':
uid = 'zofj' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zofs' + uuidV().hex[:X]
else:
uid = 'zofx' + uuidV().hex[:X]
return uid
elif type == 'grape':
if key == 'juice':
uid = 'zzgj' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zzgs' + uuidV().hex[:X]
else:
uid = 'zzgx' + uuidV().hex[:X]
return uid
elif type == 'kiwi_healthy':
if key == 'juice':
uid = 'zkij' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zkis' + uuidV().hex[:X]
else:
uid = 'zkix' + uuidV().hex[:X]
return uid
elif type == 'anar_tasty':
if key == 'juice':
uid = 'zatj' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zats' + uuidV().hex[:X]
else:
uid = 'yx' + uuidV().hex[:X]
return uid
elif type == 'apple':
if key == 'juice':
uid = 'zppj' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zpps' + uuidV().hex[:X]
else:
uid = 'zppx' + uuidV().hex[:X]
return uid
elif type == 'cherry':
if key == 'juice':
uid = 'zchj' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zchs' + uuidV().hex[:X]
else:
uid = 'zchx' + uuidV().hex[:X]
return uid
return uuidV().hex[:Y]

提前谢谢。

好吧,就简单性而言。。。

def get_uid(my_env, my_type):
i = my_env[-1]
t = type[0:2]
uid = f'z{t}t{i}z' + uuid4().hex[:6]

return uid

顺便说一句,我真的不明白最后一条返回语句的条件。您可以将None分配给my_env和my_type,如果有人为None,则返回:

def get_uid(my_env=None, my_type=None):
if my_env == None or my_type == None:
return uuid4().hex[:18]
else:
i = my_env[-1]
t = type[0:2]
uid = f'z{t}t{i}z' + uuid4().hex[:6]

return uid

我假设您错误地将3放入zkit3z中。这应该是zkitnz。如果我是对的,那么下面的代码做同样的功能

def get_uid(type, env):
if type in ["apple", "grape", "kiwi"]:
if env in ["test1", "test2"]:
uid = "z"+ type[:2]+ "t"+ env[-1]+"z" + uuid4().hex[:x]
else:
uid = "z" + type[:2] + "tnz" + uuid4().hex[:x]
return uid
return uuid4().hex[:xx]

如果3必须在zkit3z中,那么下面的代码应该继续

def get_uid(type, env):
if type in ["apple", "grape", "kiwi"]:
if env in ["test1", "test2"]:
uid = "z"+ type[:2]+ "t"+ env[-1]+"z" + uuid4().hex[:x]
else:
if type != "kiwi":
uid = "z" + type[:2] + "tnz" + uuid4().hex[:x]
else:
uid = "z" + type[:2] + "t3z" + uuid4().hex[:x]
return uid
return uuid4().hex[:xx]

最新更新