python3使用编程技巧进阶笔记1

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']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

guizhouspiderman

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值