DEV Community

Cover image for filter() in Python
Z. QIU
Z. QIU

Posted on • Updated on

filter() in Python

Ce matin, je prends qq minutes pour apprendre la fonction filter() de Python. Voici mes notes. Pour l'info, je suis ce tutorial de ce site:

https://www.liaoxuefeng.com/wiki/1016959663602400/1017404530360000

============= notes begins here =============
map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。

###  function used for filter() should return result of boolean type

def is_odd(n):
    return n % 2 == 1

a = list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
print(a)    # 结果: [1, 5, 9, 15]

def not_empty(s):
    return s and s.strip()

b = list(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))
print(b)    # 结果: ['A', 'B', 'C']
Enter fullscreen mode Exit fullscreen mode

Voici un petit exemple pour tester.

##  check if n is in format such like 121, 1331, 34543, 123321, etc... 

def is_palindrome(n):
    res = []
    while True:
        a = n % 10
        n = n // 10
        res.append(a)

        if n == 0 :
            break
    l = len(res) 
    bool_res = True
    for i in range(0, l//2):
        bool_res = bool_res and (res[i] == res[l-i-1])
        if not bool_res:
            break
    return bool_res


### 测试:
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
    print('测试成功!')
else:
    print('测试失败!')
Enter fullscreen mode Exit fullscreen mode

Ce que j'ai eu de ce test:

Alt Text

Top comments (0)