sorted排序
sorted: 对可迭代的对象进行排序操作参数:
iterable: 可迭代对象
key: 指定根据某个元素进行排序
reverse: 排序规则,reverse = True 降序 , reverse = False 升序(默认
sort 是针对 list 进行排序
1.对列表进行排序:
from random import randint
_list = [randint(-5, 20) for i in range(20)]
sort_list = sorted(_list, reverse=True)
2.对字典元素进行排序
_dict = {'a': 10, 'b': -5, 'c':6, 'e':30, 'h':14}
sort_dict = sorted(_dict.items(), key=lambda x: x[1])
print(dict(sort_dict))
3.对list元素是dict的元素进行排序
_dict_list = [{'name': '张三', 'age': 20}, {'name': '李四', 'age': 18}, {'name': '王五', 'age': 27}, {'name': '丽丝', 'age': 43}]
_sort = sorted(_dict_list, key=lambda x: x.get('age', 0), reverse=True)
print(_sort)
4.对list元素是元组的数据进行排序:
_tuple = [(1, 2), (4, 5), (6, 7), (-9, 6)]
s_tuple = sorted(_tuple)
print(s_tuple)
5. 对列表元素是字典的数据, 进行多字段排序, 实际是按照元组来排序,
_list = [{'name': '小明', 'math_score': 90, 'chinese_score': 70},
{'name': '小洪', 'math_score': 70, 'chinese_score': 95},
{'name': '小可', 'math_score': 93, 'chinese_score': 67},
{'name': '小满', 'math_score': 56, 'chinese_score': 90},
]
sort_data = sorted(_list, key=lambda x: (x.get('math_score'), -x.get('chinese_score')), reverse=True)
map
map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
1. 对可迭代对象中的每个元素, 进行平方, 然后返回
def mul(x):
return x * x
data = map(mul, list(range(1, 6)))
print(list(data))
2.求两个列表对应位置元素之和
map(lambda x, y: x + y, [1, 3, 5, 7, 9], [4, 6, 7, 8, 9])
reduce
reduce把一个函数作用在一个序列[x1, x2, x3, …]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
1.事例应用
from functools import reduce
def fun(x, y):
return x*10 + y
data = reduce(fun, [1, 3, 5, 7, 9])
print(data)
计算过程:((10+3)*10 +5)*10+7)*10+9
2. 事例, 把字符串转换成int, 并进行计算
from functools import reduce
def fn(x, y):
return x * 10 + y
def char2num(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits[s]
data = reduce(fn, map(char2num, '13579'))
filter
filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素
根据第一个参数, 筛选符合条件的数据, 并返回
1.事例应用
def func(n):
return n >9
data = list(filter(func, [1, 2, 4, 5, 6, 9, 10, 15]))
Counter
Counter: 用于追踪值的出现次数
可以应用于: 统计列表/ 字符串中, 每个元素出现的次数
1.统计列表各个元素出现的次数
from collections import Counter
_list = [randint(10, 30) for i in range(50)]
_dict = dict(Counter(_list))
2.统计字符串出现的次数
_str = Counter('aabbchadfgenmcvdfe')
print(_str)
zip
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
1.两个列表进行打包, 返回列表
a = [1, 2, 3, 4]
b = [6, 7, 8, 0]
_zip = zip(a, b)
print(list(_zip))
2.两个列表打包, 返回字典
a = ['a', 'b', 'c', 'd']
b = [6, 7, 8, 0]
_zip = zip(a, b)
print(dict(_zip))