Python's filter function

Let me first give you a request, how do you think about writing it?

Filter to people starting with s

movie_people=['s_lal','wupeiqi','s_wu','s_al']
#Maybe your first thought is to use a for loop to deal with this problem
movie_people=['s_lal','wupeiqi','s_wu','s_al']
# ret = []
# for p in movie_people:
#     if not p.startswith('s'):
#         ret.append(p)
# print ret

 Converted to function writing:

#Specific functions are placed in the function
def filter_test(array):
    ret = []
    for p in array:
        if not p.startswith('s'):
            ret.append(p)
    return right
res = filter_test(movie_people)
print res

 Then the problem comes again, the above method is not concise enough, and the following method comes to mind

def s_show(n):
    return n.startswith('s')
def filter_test(func,array):
    ret = []
    for p in array:
        if not func(p):
            ret.append(p)
    return right
res = filter_test(s_show,movie_people)
print res

 Still not concise enough, after learning anonymous functions, you can completely replace them with anonymous functions

 
def filter_test(func,array):
    ret = []
    for p in array:
        if not func(p):
            ret.append(p)
    return right
res = filter_test(lambda x: not x.startswith('s'),movie_people)
print list(res)
 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324884907&siteId=291194637