python3练习题:1-10
#practice1:在字典、列表、集合中按条件筛选数据
一般情况下,列表解析快一点。。。
#practice2:为元组中每个元素命名
- 法一:用伪常亮+序列拆包
- 法二:用namedtuple函数
#practice3:统计序列中元素出现频率
案例1
- 方法一:dict.fromkeys函数+字典排序
- 方法二:使用collections.Counter类
查找一段文本中出现最高的十个短语
import subprocess from collections import Counter out_bytes = subprocess.check_output(['netstat','-a']) out_text = out_bytes.decode('utf-8') print(type(out_text)) print(out_text)out_text = out_text.split() wordcounter = Counter(out_text) print(wordcounter.most_common(10))#practice4:把字典按value排序
- 方法1:zip + sorted
注意:以下几个函数或类的参数与返回值(学会使用help()
zip输入参数:iterable;返回值:zip对象(也是iterable)
sorted函数参数:iterable;返回值:list!!!
平常使用的list(a),并非是在调用函数,而是进行list内置类的实例化;输入:iterable;输出:lsit。
- 方法二:借助sorted的key参数
#practice5:找寻多个字典的公共key
- 方法一:循环
方法二:用dict.keys方法
- 两种实现方法
#practice6:可迭代对象与迭代器对象
Python 的迭代协议需要 _iter_() 方法返回一个实现了 _next_() 方法的迭代器对象。
3.1 方案一:迭代器方案
3.1.1 实现迭代器
import requests import pprint #测试代码 # r = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=%E5%8C%97%E4%BA%AC') # pprint.pprint(r.json())#实现一个迭代器 from collections import Iterator#构造迭代器 class WeatherIterator(Iterator):def __init__(self,cities):self.cities = citiesself.index = 0def getweather(self,city):r = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=' + city)dict_data = r.json()['data']['forecast'][0]return "%s:%s,%s" % (city,dict_data['low'],dict_data['high'])def __next__(self):if self.index == len(self.cities):raise StopIterationcity = self.cities[self.index]self.index += 1return self.getweather(city)#生成迭代器对象 weatheriterator = WeatherIterator([u'北京',u'南京',u'上海']) #迭代器对象调用next()方法 print(weatheriterator.__next__()) print(weatheriterator.__next__()) print(weatheriterator.__next__()) #没有定义__iter__方法,不是可迭代对象,所以暂时无法for in3.1.2 实现可迭代类
ather(self,city):r = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=' + city)dict_data = r.json()['data']['forecast'][0]return "%s:%s,%s" % (city,dict_data['low'],dict_data['high'])def __next__(self):if self.index == len(self.cities):raise StopIterationcity = self.cities[self.index]self.index += 1return self.getweather(city)class WeatherIterable(Iterable):def __init__(self,cities):self.cities = citiesdef __iter__(self):#返回迭代器对象return WeatherIterator(self.cities)#生成可迭代对象 weatheriterable = WeatherIterable([u'北京',u'南京',u'上海'])#for in 遍历机制的伪过程 #第一步:weatheriterable = weatheriterable.__iter__(),weatheriterable变成了迭代器对象WeatherIterator(self.cities) #第二步:遍历一次,就调用一次weatheritearble.next(),即WeatherIterator(self.cities).__next__(),最终返回值为天气信息字符串,赋值给x for x in weatheriterable:print(x)这是最标准的python迭代协议;需要建两个类,比较繁琐
3.2 方案二、合并两个类,最终使用一个类,来实现可迭代类(对方案一的简化)
from collections import Iterator,Iterable import requestsclass WeatherIterable(Iterable):def __init__(self,cities):self.cities = citiesself.index = 0def __iter__(self):#返回迭代器对象return selfdef getweather(self,city):r = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=' + city)dict_data = r.json()['data']['forecast'][0]return "%s:%s,%s" % (city,dict_data['low'],dict_data['high'])def __next__(self):if self.index == len(self.cities):raise StopIterationcity = self.cities[self.index]self.index += 1return self.getweather(city)weatheriterable = WeatherIterable([u'北京',u'南京',u'上海'])#伪过程 #第一步:weatheriterable = weatheriterable.__iter__(),返回weatheriterable对象本身 #对象本身就有__next__方法,是的迭代器对象;这样就满足了python迭代协议 #第二步:遍历一次,就调用一次weatheritearble.__next__(),最终返回值为天气信息字符串,赋值给x for x in weatheriterable:print(x)上述weatheriterable即是可迭代对象,又是迭代器对象
3.3 方案三:iter与next进一步合并,将iter方法定义为生成器(推荐)
from collections import Iterator,Iterable import requestsclass WeatherIterable(Iterable):def __init__(self,cities):self.cities = citiesself.index = 0def __iter__(self):for x in range(len(self.cities)):city = self.cities[self.index]self.index += 1yield self.getweather(city) def getweather(self,city):r = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=' + city)dict_data = r.json()['data']['forecast'][0]return "%s:%s,%s" % (city,dict_data['low'],dict_data['high'])weatheriterable = WeatherIterable([u'北京',u'南京',u'上海']) #伪过程 #第一步:weatheriterable = weatheriterable.__iter__(),调用生成器,返回__iter__生成器的生成器对象 #生成器对象默认拥有__iter__与__next__方法 #所以返回生成器对象也可以视作返回迭代器对象,符合python迭代协议 #第二步:遍历一次,就调用一次【迭代器对象】.__next__(),最终返回值为天气信息字符串,赋值给x #yield的背后可能就是调用__next__,哈哈 for x in weatheriterable:print(x)与正向迭代流程完全相同,只不过要在可迭代类中定义内置方法reversed。
from collections import Iterator,Iterable import requestsclass WeatherIterable(Iterable):def __init__(self,cities):self.cities = citiesself.index = 0def __iter__(self):for x in range(len(self.cities)):city = self.cities[self.index]self.index += 1yield self.getweather(city) def __reversed__(self):#在这个函数内设计代码,实现反向逻辑即可for x in range(len(self.cities)):self.index -= 1city = self.cities[self.index]yield self.getweather(city) def getweather(self,city):r = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=' + city)dict_data = r.json()['data']['forecast'][0]return "%s:%s,%s" % (city,dict_data['low'],dict_data['high'])weatheriterable = WeatherIterable([u'北京',u'南京',u'上海'])for x in weatheriterable:print(x) print("*"*20) for x in reversed(weatheriterable):print(x)islice(a,3)表示0:3;islice(a,3,None)表示3:结束;不可以用负数index进行切片!
#practice7:字符串拆分
#practice8:判断字符串开头/结尾是某个字符串
- 简单示例,使用字符串方法startwith与endwith
- 文件、命令相关操作补充
- 实际实例
关于stat模块:
https://www.cnblogs.com/maseng/p/3386140.html
#practice9:文本字符串替换(正则表达式分组的使用)
import rewith open('/var/log/dpkg.log') as f:text = f.read() #注意:re.sub并不会对text做出改变,而是返回新的字符串! new_text = re.sub(r'(\d{4})-(\d{2})-(\d{2})',r'(\1)(\2)(\3)',text) ''' 也可以换一种写法(使用分组名称): new_text = re.sub(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})',r'(\g<year>)(\g<month>)(\g<day>)',text) ''' print(text) print(new_text)#practice10:字符串拼接(join方法)与字符串对齐
字符串对齐
方法一: 调用字符串方法
方法二: format函数
- 实际应用
总结
以上是生活随笔为你收集整理的python3练习题:1-10的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: ubuntu18.04(python3.
- 下一篇: python3练习题:11-20