作為一個多年來一直在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
添加回答
舉報
0/150
提交
取消