亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python循環訪問正則表達式模式的列表/字典并提取字符串的方式

Python循環訪問正則表達式模式的列表/字典并提取字符串的方式

繁花不似錦 2022-08-02 10:29:13
作為一個多年來一直在R中編寫所有內容的人,我仍然不確定我是否以python中的最佳方式處理迭代/列表理解。例如,假設我有一個字符串:string = "Imported as of 1 Jan 2020"我想從字符串中構建一個日期對象,其中我的模式存儲在R中或python中,如下所示:named listdictdates_r =  list(    day = '[0-9]{1,2}(?=\\s+)',    month = '(\\w+)(?=(\\s)[0-9]{4})',    year = '[0-9]{4}$')dates_py = {    'day':r'[0-9]{1,2}(?=\s+)',    'month':r'(\w+)(?=(\s)[0-9]{4})',    'year':r'[0-9]{4}$'}在R中,我可以簡單地:> dates_out_r <- mapply(stringi::stri_extract_all_regex, pattern = dates_r, str = string, simplify = F)> dates_out_r $day[1] "1"$month[1] "Jan"$year[1] "2020"有沒有比我目前在python中更好的方法?dates_py = {    'day': r'[0-9]{1,2}(?=\s+)',    'month': r'(\w+)(?=(\s)[0-9]{4})',    'year': r'[0-9]{4}$'}dates_out = {}for key, value in dates_py.items():    rgx = re.compile(value)    dates_out[key] = re.search(rgx, date_str)[0]dates_out{'day': '1', 'month': 'February', 'year': '2020'}
查看完整描述

1 回答

?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

你可以使用dict理解
,它與循環相同,但更短for

d = {k: re.search(regex, string)[0] for k, regex in dates_py.items()}

還有一種等效的mapply,但看起來很丑陋(至少在我的實現中)

dict(map(lambda k, regex: (k, re.search(regex, string)[0]), dates_py.keys(), dates_py.values()))

另請注意,不處理這種情況,處理會添加更多事件代碼,這對于單行代碼來說并不酷re.search(...) is None


查看完整回答
反對 回復 2022-08-02
  • 1 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號