Python filter sorted
原创转载请注明出处: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