社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

dawg

dawg 最近创建的主题
dawg 最近回复了
4 年前
回复了 dawg 创建的主题 » Python:如何从OrderedDict中选择每种类型的n个元素?

你可以用 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')]
7 年前
回复了 dawg 创建的主题 » Python失败中的可选正则表达式组
  1. 通过添加 ?
  2. 提出一个替代方案 \s*\Z 对于最后一个组中的文件结尾

就像这样:

(?:Information\sLocation\n.*\n)([\W\w]+?)(?:Geolocation|\s*\Z)

Demo