Python filter sorted

本文介绍了Python内置函数filter()和sorted()的应用案例,包括过滤序列、求取素数及对列表进行排序等。通过实例展示了如何使用这些函数实现高效的数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原创转载请注明出处:http://agilestyle.iteye.com/blog/2330331

 

Python内置的filter()函数用于过滤序列

过滤偶数

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


# [1, 3, 5, 7, 9]
print(list(filter(is_odd, list(range(1, 10)))))

过滤空字符串

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


# ['a', 'b']
print(list(filter(not_empty, ['a', 'b', '', None])))

Console Output


 

用filter求30以内的素数

def odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n


def not_divisible(n):
    return lambda x: x % n > 0


def primes():
    yield 2
    it = odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(not_divisible(n), it)


for i in primes():
    if i < 30:
        print(i)
    else:
        break

Console Output


 

Python内置的sorted()函数就可以对list进行排序

# [-55, -44, 22, 33, 66, 77, 88]
print(sorted([88, 77, 66, -55, -44, 33, 22]))
# [22, 33, -44, -55, 66, 77, 88]
print(sorted([88, 77, 66, -55, -44, 33, 22], key=abs))
# ['HBase', 'HDFS', 'Hadoop', 'Hive', 'MapReduce']
print(sorted(['Hadoop', 'HDFS', 'MapReduce', 'Hive', 'HBase']))
# ['Hadoop', 'HBase', 'HDFS', 'Hive', 'MapReduce']
print(sorted(['Hadoop', 'HDFS', 'MapReduce', 'Hive', 'HBase'], key=str.lower))
# ['MapReduce', 'Hive', 'HDFS', 'HBase', 'Hadoop']
print(sorted(['Hadoop', 'HDFS', 'MapReduce', 'Hive', 'HBase'], key=str.lower, reverse=True))

Console Output


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值