我有下面的字典串列
rec=[{
'Name': 'aRe',
'Email': '[email protected]',
'timestamp': '2021-11-29T04:33:28.138522Z'
},
{
'Name': 'Umar',
'Email': '[email protected]',
'timestamp': '2021-11-28T04:33:28.138522Z'
},
{
'Name': 'Are',
'Email': '[email protected]',
'timestamp': '2021-11-27T04:33:28.138522Z'
},
{
'Name': 'arE',
'Email': '[email protected]',
'timestamp': '2021-11-28T06:59:58.975864Z'
},
{
'Name': 'umaR',
'Email': '[email protected]',
'timestamp': '2021-11-29T04:33:28.138522Z'
},
{
'Name': 'Sc',
'Email': '[email protected]',
'timestamp': '2022-02-01T15:02:12.301701Z'
}
]
- 如果存在重復的 id,則提取具有最新時間戳的字典
預計出局
[{'Name': 'umaR',
'Email': '[email protected]',
'timestamp': '2021-11-29T04:33:28.138522Z'},
{'Name': 'aRe',
'Email': '[email protected]',
'timestamp': '2021-11-29T04:33:28.138522Z'},
{'Name': 'Sc',
'Email': '[email protected]',
'timestamp': '2022-02-01T15:02:12.301701Z'}]
代碼如下
from itertools import groupby
filtered_recs = []
for key, group_iter in groupby(recs, lambda rec: rec['Name'].lower()):
recent_rec = max(group_iter, key = lambda rec: rec['timestamp'])
filtered_recs.append(recent_rec)
filtered_recs
如果所有“名稱”都在同一情況下,我的代碼作業正常。Like nameare like, 'are', 'umar', 'sc' 不適用于不規則大小寫字母
uj5u.com熱心網友回復:
首先排序recs:
from itertools import groupby
filtered_recs = []
recs = sorted(recs, key=lambda rec: rec["Name"].lower()) # <-- sort before groupby
for key, group_iter in groupby(recs, lambda rec: rec["Name"].lower()):
recent_rec = max(group_iter, key=lambda rec: rec["timestamp"])
filtered_recs.append(recent_rec)
print(filtered_recs)
印刷:
[
{
"Name": "aRe",
"Email": "[email protected]",
"timestamp": "2021-11-29T04:33:28.138522Z",
},
{
"Name": "Sc",
"Email": "[email protected]",
"timestamp": "2022-02-01T15:02:12.301701Z",
},
{
"Name": "umaR",
"Email": "[email protected]",
"timestamp": "2021-11-29T04:33:28.138522Z",
},
]
編輯:沒有排序的版本:
filtered_recs = {}
for r in recs:
filtered_recs.setdefault(r["Name"].lower(), []).append(r)
for k, v in filtered_recs.items():
filtered_recs[k] = max(v, key=lambda rec: rec["timestamp"])
print(list(filtered_recs.values()))
印刷:
[
{
"Name": "aRe",
"Email": "[email protected]",
"timestamp": "2021-11-29T04:33:28.138522Z",
},
{
"Name": "umaR",
"Email": "[email protected]",
"timestamp": "2021-11-29T04:33:28.138522Z",
},
{
"Name": "Sc",
"Email": "[email protected]",
"timestamp": "2022-02-01T15:02:12.301701Z",
},
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/465609.html
