Python.如何优化搜索功能 [英] Python. How to optimize search functions
本文介绍了Python.如何优化搜索功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以优化这两个功能?
There any way to optimize these two functions ?
第一个功能:
def searchList(list_, element):
for i in range (0,len(list_)):
if(list_[i] == element):
return True
return False
第二个功能:
return_list=[]
for x in list_search:
if searchList(list_users,x)==False:
return_list.append(x)
推荐答案
是:
return_list = [x for x in list_search if x not in list_users]
第一个函数基本上检查成员资格,在这种情况下,您可以使用 in
关键字.第二个功能可以简化为列表理解以过滤掉根据您的条件从list_search
列表中选择元素.
The first function basically checks for membership, in which case you could use the in
keyword. The second function can be reduced to a list comprehension to filter out elements from list_search
list based on your condition.
这篇关于Python.如何优化搜索功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文