我想list_of_dicts根據list_months. 一旦我從 的鍵中洗掉數字(年份),它就可以正常作業list_of_dicts,但我無法弄清楚如何在 lambda 函式中正確使用正則運算式來包含數字。
到目前為止我的代碼:
import re
list_months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
list_of_dicts = [{'Apr23': '64.401'}, {'Aug23': '56.955'}, {'Dec23': '57.453'}, {'Feb23': '90.459'}, {'Jan23': '92.731'}, {'Jul23': '56.6'}, {'Jun23': '56.509'},{'Mar23': '86.209'}, {'May23': '58.705'}, {'Nov23': '57.368'}, {'Oct23': '56.711'}, {'Sep23': '57.952'}]
r = re.compile("[a-zA-Z]{3}[0-9]{2}")
print(sorted(list_of_dicts, key=lambda d: [k in d for k in list_months if re.search(r, k)], reverse=True))
uj5u.com熱心網友回復:
這里不需要正則運算式。
dict_months = {m:i for i, m in enumerate(list_months)}
result = sorted(list_of_dicts, key=lambda d: dict_months[next(iter(d))[:3]])
print(result)
# [{'Jan23': '92.731'}, {'Feb23': '90.459'}, {'Mar23': '86.209'}, {'Apr23': '64.401'}, {'May23': '58.705'}, {'Jun23': '56.509'}, {'Jul23': '56.6'}, {'Aug23': '56.955'}, {'Sep23': '57.952'}, {'Oct23': '56.711'}, {'Nov23': '57.368'}, {'Dec23': '57.453'}]
如果您還想考慮這一天,請使用
def sortby(d):
key = next(iter(d))
return dict_months[key[:3]], int(key[3:])
result = sorted(list_of_dicts, key=sortby)
uj5u.com熱心網友回復:
使用re.subwith 的一種方式list.index。
請注意,這list.index是O(n)相當昂貴的。
def get_key_loc(dic):
k = list(dic.keys())[0]
return list_months.index(re.sub("\d ", "", k))
sorted(list_of_dicts, key=get_key_loc)
輸出:
[{'Jan23': '92.731'},
{'Feb23': '90.459'},
{'Mar23': '86.209'},
{'Apr23': '64.401'},
{'May23': '58.705'},
{'Jun23': '56.509'},
{'Jul23': '56.6'},
{'Aug23': '56.955'},
{'Sep23': '57.952'},
{'Oct23': '56.711'},
{'Nov23': '57.368'},
{'Dec23': '57.453'}]
uj5u.com熱心網友回復:
你真的不需要dict_month,使用包含的 python電池:
from datetime import datetime
sorted(list_of_dicts, key=lambda x: datetime.strptime(next(iter(x)), '%b%d'))
要么:
import dateutil.parser
sorted(list_of_dicts, key=lambda x: dateutil.parser.parse(next(iter(x))))
輸出:
[{'Jan23': '92.731'},
{'Feb23': '90.459'},
{'Mar23': '86.209'},
{'Apr23': '64.401'},
{'May23': '58.705'},
{'Jun23': '56.509'},
{'Jul23': '56.6'},
{'Aug23': '56.955'},
{'Sep23': '57.952'},
{'Oct23': '56.711'},
{'Nov23': '57.368'},
{'Dec23': '57.453'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/448685.html
