Re: [問題] 優化程式碼,轉成 dict

看板Python作者 (可愛的小松鼠)時間1年前 (2022/12/01 18:01), 1年前編輯推噓2(202)
留言4則, 2人參與, 1年前最新討論串2/3 (看更多)
https://pastebin.com/XAfGA0iY import urllib.request url = "https://admin.quic.cloud/api/dnslist" contents = urllib.request.urlopen(url).read().decode('utf-8') # 得到每一行 str_contents = contents.splitlines() # 用網頁上的 空白 短槓 空白 切割每一行 parsing = lambda s:s.split(' - ') # DNS_dict: python dictionary # DNS名字當作 key # IP位置當作 value DNS_dict = dict( [ *map(parsing, str_contents) ] ) print( DNS_dict ) ====================================================== 各位前輩好。 下面的程式碼可以執行 但我總得感覺起來沒有利落的感覺 好像用任何程式語言都可以寫出類似的東西 可以請前輩指點一二。 希望將網頁的結果轉成單純的 temp dict import urllib.request url = "https://admin.quic.cloud/api/dnslist" contents = urllib.request.urlopen(url).read().decode('utf-8') str_contents = contents.split('\n') temp = dict() for i in str_contents: if i == '': continue cdn, ip = i.split(' - ') temp[cdn] = ip -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.110.136.50 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1669885744.A.2F0.html ※ 編輯: wadd (140.110.136.50 臺灣), 12/01/2022 17:15:43 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.37.167.185 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1669888886.A.AF6.html

12/01 19:00, 1年前 , 1F
太謝謝,我要研究一下相關的用法,這才是漂亮的程式碼
12/01 19:00, 1F

12/01 19:05, 1年前 , 2F
不客氣 :)
12/01 19:05, 2F

12/01 19:06, 1年前 , 3F
還貼心的把方法都寫出來,原來是map可以對每個item
12/01 19:06, 3F

12/01 19:06, 1年前 , 4F
執行相同的function
12/01 19:06, 4F
文章代碼(AID): #1ZY7jshs (Python)
文章代碼(AID): #1ZY7jshs (Python)