1.1如何在列表中根据条件筛选
data = [4, 3, 9, 1, 5]
#筛选出data中大于1的数据
#第一种方法遍历加判断,不推荐
res1 = []
for i in data:
if i > 1:
res1.append(i)
print(res1)
#第二种方法列表解析式,推荐使用
res2 = [x for x in data if x > 1]
print(res2)
#第三种方法,用python的内置函数filter
res3 = list(filter(lambda x: x > 1, data))
#单独只是调用filter函数结果是迭代对象,得转换成列表形式才能得到筛选后的列表
1.2 如何在字典中根据条件进行筛选
#这里为了演示用了随机模块生成字典
from random import randint
#第一种方法,字典解析式
student = {'student%d' % i: randint(50, 100) for i in range(1, 21)}
res1 = {key: value for key, value in student.items() if value > 90}
print(res1)
#第二种方法,利用内置函数filter这里用了字典的内置函数items将字典转换成了嵌套元组的列表,值就是元组里面的第二个元素
res2 = dict(filter(lambda x: x[1] > 90, student.items()))
print(res2)
1.3 如何为元组中每个元素命名,提高程序可读性
from collections import namedtuple
#利用python标准库中的collections.namedtuple方法,我个人推荐这个
Student = namedtuple('student', ['name', 'age', 'sex', 'email'])
res1 = Student('red', 18, 'male', '10086@qq.com')
print(res1.name)
print(res1.age)
print(res1.sex)
print(res1.email)
>>red
>>18
>>male
>>10086@qq.com
1.4 如何对字典中的键值对按照值的大小排序
data = {'a': 20, 'b': 30, 'c': 40, 'd': 10, 'e': 5}
# 第一种方法,先按照列表解析式将字典的值和键对调位置
res1 = [(v, k) for k, v in data.items()]
# sorted方法对迭代对象里的每一个元素进行比较排序,如果是嵌套元素就按照嵌套元素里的第一个元素进行排序
res1 = sorted(res1)
# 第二种方法,用zip函数将字典中的键和值调换位值,zip函数不清楚用法的可以去了解一下
res2 = list(zip(data.values(), data.keys()))
res2 = sorted(res2)
# 第三种方法,直接用sorted函数,通过在sorted函数中设置一个匿名函数来对值进行比较,sorted函数reverse参数默认是True(升序排序)
# 我比较推荐使用这个
res3 = sorted(data.items(), key=lambda item: item[1], reverse=True)
# 对排序后的结果添加排名,运用内置函数enumerate,这是一个枚举迭代函数,返回序列中每个元素和该元素索引
res4 = {k: (i, v) for i, (k, v) in enumerate(res3, 1)}
print(res4)
1.5 如何让字典保持有序
# 方法,OrderedDict字典可是使字典在输入时保持有序
from collections import OrderedDict
from itertools import islice
from random import randint
test = OrderedDict()
test = {k: randint(2, 8) for k in 'abcde'}
print(test) #{'a': 6, 'b': 2, 'c': 8, 'd': 5, 'e': 5}
# def query_by_order(d, a, b=None):
# if b is None:
# b = a + 1
# return list(islice(d, a, b))
# islice函数是用于迭代器切片的,islice(可迭代对象,开始索引,结束索引,自定义索引跨度值)
res1 = list(islice(test, 0, 1))
res2 = list(islice(test, 0))
print(res1) #['a']
print(res2) #['a']