当前位置: 首页 > 后端技术 > Python

Python代码重构:使用any()和all()重构for循环

时间:2023-03-25 21:27:06 Python

问题描述使用for迭代一个可迭代对象,对每个对象进行条件判断,比如找到任意一个满足条件的元素,返回True,否则返回False。该操作常用于查找满足条件的元素。代码片段示例1defis_user_exist(name:str)->bool:foruserinusers:ifuser['user']==name:returnTruereturnFalse操作:判断用户是否存在In[33]:users=[{'user':'john','password':'mypassword'},{'user':'william','password':'yourpass'}]In[38]:is_user_exist('john')Out[38]:TrueIn[39]:is_user_exist('johny')Out[39]:Falserefactorusingany(iterable)refactordefis_user_exist_v2(name:str)->bool:returnany(user['user']==nameforuserinusers)runIn[43]:is_user_exist_v2('john')Out[43]:TrueIn[44]:is_user_exist_v2('johnny')Out[44]:FalseIn[45]:输入导入列表的代码片段示例2,dictdefall_user_has_password(usergroup:List[Dict])->bool:foruserinusergroup:ifuser['password']=='':returnFalsereturnTrue操作:判断用户组是否设置了密码in[49]:users_group1=[{'user':'john','password':'mypassword'},{'user':'william','password':'yourpass'}]In[50]:users_group2=[{'用户':'约翰','password':'mypassword'},{'user':'william','password':'yourpass'},{'user':'user1','password':''}]In[58]:all_user_has_password(users_group1)Out[58]:TrueIn[59]:all_user_has_password(users_group2)Out[59]:Falserefactoringusesall(iterable)forrefactoringdefall_user_has_password_v2(usergroup:List[Dict])->bool:returnall(user['password']!=''foruserinusergroup)运行中[61]:all_user_has_password_v2(users_group1)Out[61]:TrueIn[62]:all_user_has_password_v2(users_group2)Out[62]:False总结适当使用all()和any()可以有效降低代码的复杂度,并且可以有条件地判断一个可迭代对象很容易。请注意,v2的后缀是一个非常糟糕的名称。这里只是用来区分这两个函数。它不应该在代码中这样命名。请参阅内置函数—Python3.7.7文档