-
慕哥9229398
我们可以通过几个步骤来实现这一目标。要查找发生的次数,我们可以将内置过滤器与 itemgetter 结合使用。type_1from operator import itemgetterdef my_filter(item): return item['type'] == 'type_1'key = itemgetter('created_at')items = sorted(filter(my_filter, data), key=key)print(f"Num records is {len(items)}")print(f"Earliest record is {key(items[0])}")Num records is 2Earliest record is 2020-02-12T17:45:00Z相反,您可以使用生成器理解,然后对生成器进行排序。gen = (item for item in data if item['type'] == 'type_1')items = sorted(gen, key=key)# rest of the steps are the same...
-
蛊毒传说
您可以使用列表理解来获取您感兴趣的所有子列表,然后按“created_at”进行排序。l = [{'id': 'id_123', 'type': 'type_1', 'created_at': '2020-02-12T17:45:00Z'}, {'id': 'id_124', 'type': 'type_2', 'created_at': '2020-02-12T18:15:00Z'}, {'id': 'id_125', 'type': 'type_1', 'created_at': '2020-02-13T19:43:00Z'}, {'id': 'id_126', 'type': 'type_3', 'created_at': '2020-02-13T07:00:00Z'}]ll = [x for x in l if x['type'] == 'type_1']ll.sort(key=lambda k: k['created_at'])print(len(ll))print(ll[0]['created_at'])输出:202/12/2020 17:45:00
-
慕妹3146593
您可以使用 生成所有type_1s的列表,然后它们使用 with 对值进行相应的排序list_comprehensionsortdatetime.strptimefrom datetime import datetime# Generate a list with only the type_1s' created_at valuestype1s = [val['created_at'] for val in vals if val['type']=="type_1"]# Sort them based on the timestampstype1s.sort(key=lambda date: datetime.strptime(date, "%Y-%m-%dT%H:%M:%SZ"))# Print the lowest valueprint(type1s[0])#'2020-02-12T17:45:00Z'
-
jeck猫
您可以使用以下函数获取所需的输出:from datetime import datetimedef sol(l): sum_=0 dict_={} for x in l: if x['type']=='type_1': sum_+=1 dict_[x['id']]=datetime.strptime(x['created_at'], "%Y-%m-%dT%H:%M:%SZ") date =sorted(dict_.values())[0] for key,value in dict_.items(): if value== date: id_=key return sum_,date,id_sol(l)此函数给出类型 ='type_1'的次数,分别给出相应的最小日期及其 ID。希望这有帮助!
-
缥缈止盈
这是使用 和 的一种方法。filtermin前任:data = [{'id': 'id_123', 'type': 'type_1', 'created_at': '2020-02-12T17:45:00Z'}, {'id': 'id_124', 'type': 'type_2', 'created_at': '2020-02-12T18:15:00Z'}, {'id': 'id_125', 'type': 'type_1', 'created_at': '2020-02-13T19:43:00Z'}, {'id': 'id_126', 'type': 'type_3', 'created_at': '2020-02-13T07:00:00Z'}]onlytype_1 = list(filter(lambda x: x['type'] == 'type_1', data))print(len(onlytype_1))print(min(onlytype_1, key=lambda x: x['created_at']))艺术temp = {}for i in data: temp.setdefault(i['type'], []).append(i)print(len(temp['type_1']))print(min(temp['type_1'], key=lambda x: x['created_at']))输出:2{'id': 'id_123', 'type': 'type_1', 'created_at': '2020-02-12T17:45:00Z'}