python3练习题:1-10
#practice1:在字典、列表、集合中按條件篩選數(shù)據(jù)
一般情況下,列表解析快一點。。。
#practice2:為元組中每個元素命名
- 法一:用偽常亮+序列拆包
- 法二:用namedtuple函數(shù)
#practice3:統(tǒng)計序列中元素出現(xiàn)頻率
案例1
- 方法一:dict.fromkeys函數(shù)+字典排序
- 方法二:使用collections.Counter類
查找一段文本中出現(xiàn)最高的十個短語
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
注意:以下幾個函數(shù)或類的參數(shù)與返回值(學(xué)會使用help()
zip輸入?yún)?shù):iterable;返回值:zip對象(也是iterable)
sorted函數(shù)參數(shù):iterable;返回值:list!!!
平常使用的list(a),并非是在調(diào)用函數(shù),而是進行l(wèi)ist內(nèi)置類的實例化;輸入:iterable;輸出:lsit。
- 方法二:借助sorted的key參數(shù)
#practice5:找尋多個字典的公共key
- 方法一:循環(huán)
方法二:用dict.keys方法
- 兩種實現(xiàn)方法
#practice6:可迭代對象與迭代器對象
Python 的迭代協(xié)議需要 _iter_() 方法返回一個實現(xiàn)了 _next_() 方法的迭代器對象。
3.1 方案一:迭代器方案
3.1.1 實現(xiàn)迭代器
import requests import pprint #測試代碼 # r = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=%E5%8C%97%E4%BA%AC') # pprint.pprint(r.json())#實現(xiàn)一個迭代器 from collections import Iterator#構(gòu)造迭代器 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'上海']) #迭代器對象調(diào)用next()方法 print(weatheriterator.__next__()) print(weatheriterator.__next__()) print(weatheriterator.__next__()) #沒有定義__iter__方法,不是可迭代對象,所以暫時無法for in3.1.2 實現(xiàn)可迭代類
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) #第二步:遍歷一次,就調(diào)用一次weatheritearble.next(),即WeatherIterator(self.cities).__next__(),最終返回值為天氣信息字符串,賦值給x for x in weatheriterable:print(x)這是最標(biāo)準(zhǔn)的python迭代協(xié)議;需要建兩個類,比較繁瑣
3.2 方案二、合并兩個類,最終使用一個類,來實現(xiàn)可迭代類(對方案一的簡化)
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迭代協(xié)議 #第二步:遍歷一次,就調(diào)用一次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__(),調(diào)用生成器,返回__iter__生成器的生成器對象 #生成器對象默認(rèn)擁有__iter__與__next__方法 #所以返回生成器對象也可以視作返回迭代器對象,符合python迭代協(xié)議 #第二步:遍歷一次,就調(diào)用一次【迭代器對象】.__next__(),最終返回值為天氣信息字符串,賦值給x #yield的背后可能就是調(diào)用__next__,哈哈 for x in weatheriterable:print(x)與正向迭代流程完全相同,只不過要在可迭代類中定義內(nèi)置方法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):#在這個函數(shù)內(nèi)設(shè)計代碼,實現(xiàn)反向邏輯即可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:結(jié)束;不可以用負(fù)數(shù)index進行切片!
#practice7:字符串拆分
#practice8:判斷字符串開頭/結(jié)尾是某個字符串
- 簡單示例,使用字符串方法startwith與endwith
- 文件、命令相關(guān)操作補充
- 實際實例
關(guān)于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方法)與字符串對齊
字符串對齊
方法一: 調(diào)用字符串方法
方法二: format函數(shù)
- 實際應(yīng)用
總結(jié)
以上是生活随笔為你收集整理的python3练习题:1-10的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu18.04(python3.
- 下一篇: sublime3(anaconda) 无