python内置函数(二)之filter,map,sorted

filter

filter()函数接收一个函数 f 和一个iterable的对象,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件(False)的元素,返回由符合条件元素组成的新可迭代filter对象。

def is_odd(x):
    return x % 2 == 1
list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17]))

结果:[1, 7, 9, 17]

适用情景:

利用filter(),可以完成很多有用的功能,例如,删除 None 或者空字符串:

def is_not_empty(s):
    return s and len(s.strip()) > 0
>>>list(filter(is_not_empty, ['test', None, '', 'str', '  ', 'END']))

结果:['test', 'str', 'END']

注意: s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')。

 

map

map函数应用于每一个可迭代的项,返回的是一个结果map可迭代对象。如果有其他的可迭代参数传进来,map函数则会把每一个参数都以相应的处理函数进行迭代处理。map()函数接收两个参数,一个是函数,一个是可迭代对象,map将传入的函数依次作用到序列的每个元素,并把结果作为新的map可迭代对象<map at 0x13322f34cf8>返回。

有一个list, L = [1,2,3,4,5,6,7,8],我们要将f(x)=x^2作用于这个list上,那么我们可以使用map函数处理。

def is_odd(x):
    return x % 2 == 1
def square(x):
    return x**2
list(map(is_odd, [1, 4, 6, 7, 9, 12, 17]))
list(map(square, [1, 4, 6, 7, 9, 12, 17]))

结果:

[True, False, False, True, True, False, True]

[1, 16, 36, 49, 81, 144, 289]

sorted

对List、Dict进行排序,Python提供了两个方法对给定的List L进行排序:
方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本
方法2.用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变

l = [1,3,5,-2,-4,-6]
l1= sorted(l)
l2 = sorted(l,key=abs)
print(l1)
print(l2)

结果:

[-6, -4, -2, 1, 3, 5]
[1, -2, 3, -4, 5, -6]

l = [[1,2],[3,4,5,6],(7,),'123']
print(sorted(l,key=len))

结果:[(7,), [1, 2], '123', [3, 4, 5, 6]]

 

猜你喜欢

转载自www.cnblogs.com/wqbin/p/10220938.html
今日推荐