filter

Reads: 774 Edit

filter()可以根据过滤函数对列表中的元素进行过滤

1 过滤负数

def is_pos(a):
    return a >= 0


x = [41, -68, 47, -87, 39, -46, 102, -77, 51]
y = filter(is_pos, x)

print(list(y))

运行结果:

[41, 47, 39, 102, 51]

2 过滤非质数

def is_comp(a):
    if a <= 1:							# 过滤小于1的数
        return False
    if a-int(a) != 0:					# 过滤非整数
        return False
    if a == 2:							# 2是质数,保留
        return True
    for i in range(2,a):
        if a % i == 0:
            return False			# 可以被除1和自身外整除,过滤
    return True


x = range(1,101)
y = filter(is_comp, x)

print(list(y))

运行结果:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Comments

Make a comment