你可以用
islice
用一个生成器来对照列表:
from collections import OrderedDict
import itertools as it
odl=[OrderedDict([('id', '1'), ('date', '2022-01-08'), ('type', 'A')]), OrderedDict([('id', '2'), ('date', '2022-01-09'), ('type', 'A')]), OrderedDict([('id', '3'), ('date', '2022-01-08'), ('type', 'B')]), OrderedDict([('id', '4'), ('date', '2022-01-09'), ('type', 'B')]),
OrderedDict([('id', '5'), ('date', '2022-01-08'), ('type', 'C')]), OrderedDict([('id', '6'), ('date', '2022-01-09'), ('type', 'C')])]
n=3
>>> list(it.islice((t for od in odl for t in od.items() if t[0]=='type'),0,n))
[('type', 'A'), ('type', 'A'), ('type', 'B')]
如果你想
n
每种类型,然后使用
groupby
同样
艾利斯
:
n=1
for k,v in it.groupby(sorted(odl, key=lambda od: od['type']), key=lambda od: od['type']):
print(list(it.islice((t for od in v for t in od.items() if t[0]=='type'),0,n)))
印刷品:
[('type', 'A')]
[('type', 'B')]
[('type', 'C')]