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 ...
随机推荐
- IDEA提示找不到Mapper接口:Could not autowire.No beans of 'xxxMapper' type found
前言 相信大多数互联网公司的持久层框架都是使用 Mybatis 框架,而大家在 Service 层引入自己编写的 Mapper 接口时应该会遇到下面的情况: 我们可以看到,上面的红色警告在提示我们,找 ...
- 【React Native】进阶指南之一(特定平台、图片加载、动画使用)
一.特定平台代码 React Native提供了两种方法来区分平台: 使用Platform模块: 使用特定平台扩展名: 1.Platform模块 React Native提供了一个检测当前运行平台的模 ...
- 使用VSCode创建一个Vue项目
vue-cli 是vue.js的脚手架,用于自动生成vue.js模板工程的. 安装vue-cli之前,需要先安装了vue和webpack · node -v //(版本低引起:bas ...
- Saltstack_使用指南15_多master
1. 主机规划 实现2个master,当这两个master运行时都可以向minion发送命令. salt 版本 [root@salt100 ~]# salt --version salt (Oxyge ...
- redis5.0.4安装配置
1.下载redis wget http://download.redis.io/releases/redis-5.0.4.tar.gz 2.解压到opt目录 tar -zxvf redis-5.0.4 ...
- 飞思卡尔K60时钟分析
推荐:NXP官方软件config tool,图形化界面可导出代码 K60芯片的时钟系统由振荡器(OSC).实时振荡器(RTC OSC).多功能时钟发生器(MCG).系统集成模块(SIM)和电源管理器( ...
- 手机号码生成器app有吗,怎么使用的呢?
手机号码生成器app是有的,他有手机号码生成器安卓版,也有手机号码生成器苹果版的.很多人会误解他的功能以为是拿来生成号码来接验证码的,其实他不是拿来接短信的.它是用来给别人做营销找客沪的找客源的,接不 ...
- You Are Given a Decimal String... CodeForces - 1202B [简单dp][补题]
补一下codeforces前天教育场的题.当时只A了一道题. 大致题意: 定义一个x - y - counter :是一个加法计数器.初始值为0,之后可以任意选择+x或者+y而我们由每次累加结果的最后 ...
- Codeforces Round #603 (Div. 2) C. Everyone is a Winner! 二分
C. Everyone is a Winner! On the well-known testing system MathForces, a draw of n rating units is ar ...
- Linux下修改Mysql密码的三种方式
前言 有时我们会忘记Mysql的密码,或者想改一个密码,以下将对这两种情况修改密码的三种解决方法做个总结 本文都以用户为 root 为例 一.拥有原来的myql的root的密码 方法一: 在mysql ...