日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python3练习题:1-10

發布時間:2025/10/17 python 10 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python3练习题:1-10 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

#practice1:在字典、列表、集合中按條件篩選數據

  • 列表解析
  • #如何在列表、字典、集合中按條件篩選數據 from random import randint from timeit import timeit #因為for提取的變量在randint函數中未使用,所以用_,而非一個變量名 a = [randint(-10,10) for _ in range(10)] print(a) #方法1 b = filter(lambda x: x > 0,a) print(list(b)) #方法2 c = [x for x in a if x > 0] print(c) #測試速度 print(timeit("[x for x in a if x > 0]","from __main__ import a",number=10)) print(timeit("filter(lambda x: x > 0,a)","from __main__ import a",number=10))

    一般情況下,列表解析快一點。。。

  • 字典解析
  • from random import randint d = {x:randint(-10,10) for x in range(10)} print(d) #字典解析 result = {v:k for k,v in d.items() if v > 0} print(result) #不適合用filter

  • 字典解析
  • from random import randinta = {randint(-20,20) for _ in range(10)}print(a) result = {x for x in a if x > 0} print(result)


    #practice2:為元組中每個元素命名

    • 法一:用偽常亮+序列拆包
    • 法二:用namedtuple函數
    student = ('jim',18,'shanxi','china')#方法一:偽常亮 #增添了全局變量,不推薦 NAME,AGE,PROVINCE,COUNTRY = range(4) print(student[NAME]) print(student[AGE])#方法二:使用namedtuple from collections import namedtuple#參數1:namedtuple函數返回一個Tuple子類,第一個參數是子類名稱;參數2:index名稱列表 Student = namedtuple('Student',['name','age','province','country']) #Student元組類實例化,s是一個帶名稱的元組 s = Student('jim',18,'shanxi','china') print(s.name)


    #practice3:統計序列中元素出現頻率

  • 案例1

    • 方法一:dict.fromkeys函數+字典排序
  • from random import randintl = [randint(0,10) for _ in range(20)] print(l)#方法一:使用dict.fromkeys構建字典,用value來計數 #fromkeys方法構建的字典會自動去重 mydict = dict.fromkeys(l,0) print(mydict) #計算頻率 for x in l:mydict[x] += 1 print(mydict) #把字典轉化為類列表,然后用sorted+key關鍵字按序排列 print((mydict.items())) newdict = sorted(mydict.items(),key=lambda x:x[1]) print(newdict) #取出頻率最高的三個 newdict = newdict[-3:] print(newdict)

    • 方法二:使用collections.Counter類
    from random import randint from collections import Counterl = [randint(0,10) for _ in range(20)] print(l)countdict = Counter(l) #countdict是一個類字典對象,因為Counter繼承了內置Dict類,所以countdict擁有所有字典的方法! #countdict還有新方法most_common print(countdict) #返回3個頻率最高的單元,默認由高到低 print(countdict.most_common(3))

  • 案例2
  • 查找一段文本中出現最高的十個短語

    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
    from random import randintd = {str(k):randint(0,10) for k in range(10)} #d.items返回值:類集合對象 print(d.items())#方法一:用zip將key與value列表組合成新的元組列表 #對元組列表執行sorted方法 result = zip(d.values(),d.keys()) #zip后里面的基本單元是tuple,這是永遠不變的 #外邊可以轉換為list/set/tuple來包裹 new_result = sorted(result) print(new_result)

    注意:以下幾個函數或類的參數與返回值(學會使用help()

    zip輸入參數:iterable;返回值:zip對象(也是iterable)

    sorted函數參數:iterable;返回值:list!!!

    平常使用的list(a),并非是在調用函數,而是進行list內置類的實例化;輸入:iterable;輸出:lsit。

    • 方法二:借助sorted的key參數
    from random import randintd = {str(k):randint(0,10) for k in range(10)} #dict.items()返回一個dict_items對象,是個類集合對象,而且是個iterable for x in d.items():#從結果可知,基本元素是個元組!print(x) #用key參數制定排序對象 result = sorted(d.items(),key=lambda x:x[1]) print(result)


    #practice5:找尋多個字典的公共key

    • 方法一:循環
    • 方法二:用dict.keys方法

    • 兩種實現方法
    from random import randintgame1 = {x:randint(1,3) for x in "abcdef"} print(game1) game2 = {x:randint(1,3) for x in "abckew"} print(game2) game3 = {x:randint(1,3) for x in "mnef"} print(game3)#法1:for循環 res = [] for k in game1:if k in game2 and k in game3:res.append(k)print(res)#法2:利用dict.keys方法,返回值是個類集合對象 result = game1.keys() & game2.keys() & game3.keys() print(result)

  • pythonic
  • from random import randint from functools import reduce game1 = {x:randint(1,3) for x in "abcdef"} print(game1) game2 = {x:randint(1,3) for x in "abckew"} print(game2) game3 = {x:randint(1,3) for x in "mnef"} print(game3)#注意:func不能直接為keys!! #map函數返回值為iterator a = map(dict.keys,[game1,game2,game3]) result = reduce(lambda x,y: x & y,a) print(result)

    #practice6:可迭代對象與迭代器對象

  • 概念區分
  • 各種可迭代實現方案的總依循:python的迭代協議
  • 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 in

    3.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 方案三:iternext進一步合并,將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)

  • 可迭代對象切片
  • from collections import Iterator,Iterable import requests from itertools import isliceclass 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'上海',u'廣州']) #weatheriteterable是可迭代對象,但不是迭代器對象 #網上有的將islice操作稱為迭代器切片;但個人認為可迭代對象切片更準確 print(dir(weatheriterable)) for x in islice(weatheriterable,0,2):print(x)

    islice(a,3)表示0:3;islice(a,3,None)表示3:結束;不可以用負數index進行切片!


    #practice7:字符串拆分

  • 方法一:自己設計函數(使用字符串處理函數split)
  • def mysplit(s,split_keys):#a為初始列表,字符串轉列表的方法如下a = [s]for split_key in split_keys:#t為分割后的暫時列表t = []#list操作是必須的,否則t.extend無法生效#Python中即使某個操作有返回值,也可以不賦值list(map(lambda x: t.extend(x.split(split_key)),a))##將分割后的列表賦值給初始列表,進入下一輪循環a = treturn as = 'ab;cd|efg|hi,jkl|mn\topq;rst,uvw\txyz' result = mysplit(s,';,|\t') print(result)

  • 方法二:re.split函數
  • import res = 'ab;cd|efg|hi,jkl|mn\topq;rst,uvw\txyz' result = re.split(r'[;|,\t]+',s) print(result)


    #practice8:判斷字符串開頭/結尾是某個字符串

    • 簡單示例,使用字符串方法startwith與endwith
    import osfiles = os.listdir('/home/openlab') print(files) for x in files:if x.endswith('.py'):print('*'*20 + x)#注意:不是elseif#startswith與endswith使用多個參數時,只能用元組將參數括起來,參數間關系為或!elif x.startswith(('.s','.x')):print('#'*20 + x)

    • 文件、命令相關操作補充
    import subprocess,os#調用check_output,執行命令并返回結果 out_bytes = subprocess.check_output(['ls','-l']) out_text = out_bytes.decode('utf-8') print(out_text) #調用system函數,執行命令并將狀態碼返回 return_code = os.system('touch 1.txt') print(return_code)import stat #返回stat對象 result = os.stat('p2.py') #返回十進制的文件mode(包括權限等一系列信息) print(result.st_mode) #轉換為八進制便于觀察 print(oct(result.st_mode))

    • 實際實例
    import os,stat import subprocessdef show_status(path='.'):output_bytes = subprocess.check_output(['ls','-l',path])output_text = output_bytes.decode('utf-8')print(output_text)show_status() #找當前文件夾下的Python文件,并為文件的擁有者以及相同用戶組的成員添加可執行權限 files = os.listdir('.') for file in files:if file.endswith('py'):#采用或的方式添加權限os.chmod(file,os.stat(file).st_mode | stat.S_IXGRP | stat.S_IXUSR)show_status()

    關于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方法)與字符串對齊

  • 字符串拼接
  • l = ['1','2','ss','q'] #相比于加號拼接,下列方法不僅簡潔,而且占用內存小! result = ''.join(l) print(result) result = 'AA'.join(l) print(result) #join參數是iterable即可,所以用生成器表達式生產一個generator對象(是iterable)也合理 result = ''.join((str(x) for x in range(10))) print(result)

  • 字符串對齊

    • 方法一: 調用字符串方法

    • 方法二: format函數

  • a = 'wakaka' a1 = a.ljust(20) a2 = a.rjust(20) a3 = a.center(20) print(a1) print(len(a1)) print(a2) print(a3)a1 = format(a,'<20') a2 = format(a,'>20') a3 = format(a,'^20') print(a1) print(len(a1)) print(a2) print(a3)

    • 實際應用
    from random import randint dict1 = {str(x):randint(10,20) for x in ['wakaka','dd','ffs']} #取最長值的方法 test = map(len,dict1.keys()) #map對象可以直接max! max_len = max(test) for k in dict1:print(k.ljust(max_len) + ":" + str(dict1[k]))

    總結

    以上是生活随笔為你收集整理的python3练习题:1-10的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。