内置函数--sorted,filter,map

sorted() 排序函数.

语法: sorted(Iterable, key=None, reverse=False) Iterable: 可迭代对象;  key: 排序规则(排序函数); reverse: 是否是倒叙. True: 倒叙, False: 正序

在sorted内部会将可迭代对象中的每一个元素传递给这个函 数的参数. 根据函数运算的结果进行排序.

sort 与 sorted 区别:

sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。

list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

>>>a = [5,7,6,3,4,1,2]
>>> b = sorted(a)       # 保留原列表
>>> a 
[5, 7, 6, 3, 4, 1, 2]
>>> b
[1, 2, 3, 4, 5, 6, 7]

>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=lambda s: s[2])            # 按年龄排序
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

 filter() 筛选(过滤)函数

语法: filter(function. Iterable) function: 用来筛选的函数. 在filter中会自动的把iterable中的元素传递给function. 然后 根据function返回的True或者False来判断是否保留此项数据 Iterable: 可迭代对象

lst = [{"id":1, "name":'alex', "age":18},
 {"id":2, "name":'wusir', "age":16},
 {"id":3, "name":'taibai', "age":17}]
fl = filter(lambda e: e['age'] > 16, lst) # 筛选年龄⼤于16的数据
print(list(fl))
输出结果:[{'id': 1, 'name': 'alex', 'age': 18}, {'id': 3, 'name': 'taibai', 'age': 17}]

map() 映射函数

语法: map(function, iterable) 可以对可迭代对象中的每个元素进行映射. 分别执行 function

计算列表中每个元素的平⽅ ,返回新列表
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5])))
输出结果:[1, 4, 9, 16, 25]

计算两个列表中相同位置的数据的和
lst1 = [1, 2, 3, 4, 5]
lst2 = [2, 4, 6, 8, 10]
print(list(map(lambda x, y: x+y, lst1, lst2)))
输出结果: [3, 6, 9, 12, 15]
原文地址:https://www.cnblogs.com/feifeifeisir/p/9483717.html