map()
map()
函数接收两个参数,一个是函数,一个是Iterable
,map
将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator
返回#将一个存放整型数据的列表 把元素转变成字符串类型 list0 = [12, 56, 71, 83, 29] list1 = list(map(str, list0)) print(list1)
reduce()
reduce
把一个函数作用在一个序列[x1, x2, x3, ...]
上,这个函数必须接收两个参数,reduce
把结果继续和序列的下一个元素做累积计算''' 把序列[5, 4, 3, 2, 1]变成整数54321 ''' import functools res = functools.reduce(lambda x,y:x * 10 +y,[5, 4, 3, 2, 1]) print(res) #54321
filter()
filter()
把传入的函数依次作用于每个元素,然后根据返回值是True
还是False
决定保留还是丢弃该元素。dict0 = {"语文":22, "数学":65, "政治":77} #筛选掉不及格的键值对 #字典生成式 dict1 = {k:v for k, v in dict0.items() if v >= 60} print(dict1) for item in dict0.items(): print(item) ''' ('语文', 22) ('数学', 65) ('政治', 77) ''' #filter()函数 dict2 = dict(filter(lambda x: x[1] >= 60, dict0.items())) print(dict2)
zip()
将两个个序列中的元素进行一对一的组合成元组
res = zip(["1", "2", "3"], [5, 6,7, 8]) print(res) ''' {'1': 5, '2': 6, '3': 7} 多余的将会被丢弃 ''' #将字典中的kv颠倒 res = zip(dict0.values(), dict0.keys()) dict1 = dict(res) print(dict1)
sorted()
sorted()
函数可以接收一个key
函数来实现自定义的排序,例如按绝对值大小排序#按大小排序 sorted([36, 5, -12, 9, -21]) #[-21, -12, 5, 9, 36] #按绝对值大小排序 sorted([36, 5, -12, 9, -21], key=abs) #[5, 9, -12, -21, 36] #按首字母逆序排序(忽略大小写) sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) #['Zoo', 'Credit', 'bob', 'about']