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.