8.python3实用编程技巧进阶(三)
3.1.如何实现可迭代对象和迭代器对象
#3.1 如何实现可迭代对象和迭代器对象 import requests
from collections.abc import Iterable,Iterator class WeatherIterator(Iterator):
def __init__(self,cities):
self.cities = cities
#从列表中迭代一个city,index就+1
self.index = 0 def __next__(self):
#如果所有的城市都迭代完了,就抛出异常
if self.index == len(self.cities):
raise StopIteration
#当前迭代的city
city = self.cities[self.index]
#迭代完当前city,index就+1
self.index += 1
return self.get_weather(city) def get_weather(self,city):
url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city
r = requests.get(url)
#获取当天的天气信息
data = r.json()['data']['forecast'][0]
#返回城市名字、最高和最低气温
return city, data['high'], data['low'] class WeatherIterable(Iterable):
def __init__(self,cities):
self.cities = cities def __iter__(self):
return WeatherIterator(self.cities) def show(w):
for x in w:
print(x) weather = WeatherIterable(['北京','上海','广州','深圳','东莞'])
show(weather)
结果

3.2如何使用生成器函数实现可迭代对象
#3.2如何使用生成器函数实现可迭代对象 from collections.abc import Iterable class PrimeNumbers(Iterable):
def __init__(self,a,b):
self.a = a
self.b = b def __iter__(self):
for k in range(self.a,self.b):
if self.is_prime(k):
yield k def is_prime(self,k):
return False if k < 2 else all(map(lambda x : k % x, range(2, k))) #打印1到30直接的素数
pn = PrimeNumbers(1, 30)
for n in pn:
print(n)
3.3.如何进行反向迭代以及如何实现反向迭代
反向迭代
In [75]: l = [1,2,3,4,5] In [76]: for x in l:
...: print(x)
...:
1
2
3
4
5 In [77]: for x in reversed(l):
...: print(x)
...:
5
4
3
2
1
要想实现反向迭代必须实现__reversed__方法
#3.3.如何进行反向迭代以及如何实现反向迭代 class IntRange:
def __init__(self,a,b,step):
self.a = a
self.b = b
self.step = step def __iter__(self):
t = self.a
while t <= self.b:
yield t
t += self.step def __reversed__(self):
t = self.b
while t >= self.a:
yield t
t -= self.step fr = IntRange(1, 10, 2) for x in fr:
print(x) print('=' * 30) #反向迭代
for y in reversed(fr):
print(y)
3.4.如何对迭代器做切片操作
(1)切片的实质是__getitem__方法
In [9]: l = list(range(10)) In [10]: l[3]
Out[10]: 3 In [11]: l.__getitem__(3)
Out[11]: 3 In [12]: l[2:6]
Out[12]: [2, 3, 4, 5] In [13]: l.__getitem__(slice(2,6))
Out[13]: [2, 3, 4, 5]
(2)打印文件第2~5行
islice能返回一个迭代对象切片的生成器
#3.4.如何对迭代器做切片操作
from itertools import islice
f= open('iter_islice')
#打印文件的第2~5行内容
for line in islice(f, 1, 5):
print(line)
(3)自己实现islice功能
#自己实现一个类似islice的功能
def my_slice(iterable, start, end, step=1):
for i, x in enumerate(iterable):
if i >= end:
break
if i >= start:
yield x print(list(my_slice(range(1,20), 4, 10))) #[5, 6, 7, 8, 9, 10] from itertools import islice print(list(islice(range(1,20),4, 10))) #[5, 6, 7, 8, 9, 10]
(4)加step
#3.4.如何对迭代器做切片操作
from itertools import islice
f= open('iter_islice')
#打印文件的第2~5行内容
for line in islice(f, 1, 5):
print(line)
#自己实现一个类似islice的功能
def my_slice(iterable, start, end, step=1):
tmp = 0
for i, x in enumerate(iterable):
if i >= end:
break
if i >= start:
if tmp == 0:
tmp = step
yield x
tmp -= 1
print(list(my_slice(range(1,20), 4, 10))) #[5, 6, 7, 8, 9, 10]
print(list(my_slice(range(1,20), 4, 10,2))) #[5, 7, 9]
from itertools import islice
print(list(islice(range(1,20),4, 10))) #[5, 6, 7, 8, 9, 10]
print(list(islice(range(1,20),4, 10,2))) #[5, 7, 9]
3.5.如何在一个for语句中迭代多个可迭代对象
计算学生的三科成绩总分,用zip()函数
In [25]: from random import randint In [26]: chinese = [randint(60,100) for _ in range(10)] In [27]: math = [randint(60,100) for _ in range(10)] In [28]: english = [randint(60,100) for _ in range(10)] In [29]: chinese
Out[29]: [70, 63, 85, 74, 70, 96, 60, 69, 62, 83] In [30]: math
Out[30]: [76, 81, 86, 93, 74, 83, 69, 63, 60, 80] In [31]: english
Out[31]: [100, 96, 83, 89, 71, 79, 82, 87, 81, 71] In [32]: t = [] In [33]: for s1, s2, s3 in zip(chinese, math, english):
...: t.append(s1 + s2 +s3)
...: In [34]: t
Out[34]: [246, 240, 254, 256, 215, 258, 211, 219, 203, 234]
求三个班级中分数高于90分的总人数,用chain
In [53]: c1 = [randint(60,100) for _ in range(1,10)] In [54]: c2 = [randint(60,100) for _ in range(1,10)] In [55]: c3 = [randint(60,100) for _ in range(1,10)] In [56]: c1
Out[56]: [60, 79, 89, 84, 68, 68, 89, 68, 82] In [57]: c2
Out[57]: [69, 64, 87, 89, 60, 77, 89, 81, 90] In [58]: c3
Out[58]: [80, 92, 64, 73, 68, 84, 97, 71, 65] In [59]: from itertools import chain In [60]: len([ x for x in chain(c1, c2, c3) if x > 90])
Out[60]: 2
8.python3实用编程技巧进阶(三)的更多相关文章
- Python3实用编程技巧进阶 ☝☝☝
Python3实用编程技巧进阶 ☝☝☝ 1.1.如何在列表中根据条件筛选数据 # 1.1.如何在列表中根据条件筛选数据 data = [-1, 2, 3, -4, 5] #筛选出data列表中大于等 ...
- Python3实用编程技巧进阶✍✍✍
Python3实用编程技巧进阶 整个课程都看完了,这个课程的分享可以往下看,下面有链接,之前做java开发也做了一些年头,也分享下自己看这个视频的感受,单论单个知识点课程本身没问题,大家看的时候可以 ...
- Python3实用编程技巧进阶
Python3实用编程技巧进阶 整个课程都看完了,这个课程的分享可以往下看,下面有链接,之前做java开发也做了一些年头,也分享下自己看这个视频的感受,单论单个知识点课程本身没问题,大家看的时候可以 ...
- 6.python3实用编程技巧进阶(一)
1.1.如何在列表中根据条件筛选数据 # 1.1.如何在列表中根据条件筛选数据 data = [-1, 2, 3, -4, 5] #筛选出data列表中大于等于零的数据 #第一种方法,不推荐 res1 ...
- 7.python3实用编程技巧进阶(二)
2.1.如何拆分含有多种分隔符的字符串 #2.1.如何拆分含有多种分隔符的字符串 s = 'ab;cd|efg|hi,jkl|mn\topq;rst,uvw\txyz' #第一种方法 def my__ ...
- 9.python3实用编程技巧进阶(四)
4.1.如何读写csv数据 爬取豆瓣top250书籍 import requests import json import csv from bs4 import BeautifulSoup book ...
- 10.python3实用编程技巧进阶(五)
5.1.如何派生内置不可变类型并修其改实例化行为 修改实例化行为 # 5.1.如何派生内置不可变类型并修其改实例化行为 #继承内置tuple, 并实现__new__,在其中修改实例化行为 class ...
- EF – 2.EF数据查询基础(上)查询数据的实用编程技巧
目录 5.4.1 查询符合条件的单条记录 EF使用SingleOrDefault()和Find()两个方法查询符合条件的单条记录. 5.4.2 Entity Framework中的内部数据缓存 DbS ...
- EF – 2.EF数据查询基础(上)查询数据的实用编程技巧
目录 5.4.1 查询符合条件的单条记录 EF使用SingleOrDefault()和Find()两个方法查询符合条件的单条记录. 5.4.2 Entity Framework中的内部数据缓存 DbS ...
随机推荐
- Python Web(一)
Infi-chu: http://www.cnblogs.com/Infi-chu/ 一.Web框架 1.socket网络编程 架构:C/S 协议:TCP/UDP 传输层 2.Web应用 架构:B/S ...
- 解决MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk.问题
突然发现昨天刚搭建的websocket不能连接了,提示: MISCONF Redis is configured to save RDB snapshots, but it is currently ...
- dd 工具使用; SSD 顺序写性能测试;
dd 工具使用: dd 也是我们经常使用到的磁盘测试工具,Linux服务器装好系统之后,想要知道硬盘的读写是否能满足服务的需要,如果不满足硬盘的IO就是服务的一个瓶颈.我们可以使用dd命令简单进行测试 ...
- JS运动---运动基础(匀速运动)
[一]运动基础 (2)基础运动案例 <!DOCTYPE html> <html> <head> <meta charset="utf-8" ...
- Linux下查看哪些进程占用的CPU、内存资源
1.CPU占用最多的前10个进程: ps auxw|head -1;ps auxw|sort -rn -k3|head -10 2.内存消耗最多的前10个进程 ps auxw|head -1;ps a ...
- Go 循环 (for)
循环类型 for: for a := 0; a < 10; a ++{ fmt.Println(a) } 在执行结束后 a == 10 while: a := 0 for a < 10{ ...
- 基于Django的Rest Framework框架的url控制器
本文目录 一 自定义路由(原始方式) 二 半自动路由(视图类继承ModelViewSet) 三 全自动路由(自动生成路由) 回到目录 一 自定义路由(原始方式) from django.conf.ur ...
- php精确计算
php BC高精确度函数库 结果: php一般的取余 只是除以整数 bc精度取余 精确到了小数
- C语言程序设计100例之(12):Eratosthenes筛法求质数
例12 Eratosthenes筛法求质数 问题描述 Eratosthenes筛法的基本思想是:把某范围内的自然数从小到大依次排列好.宣布1不是质数,把它去掉:然后从余下的数中取出最小的数,宣布它 ...
- Javascript模块化开发1——package.json详解
一.环境安装 Node.js 安装包及源码下载地址为:https://nodejs.org/en/download/. 在该页面你可以根据不同平台系统选择你需要的 Node.js 安装包. Node. ...