栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python分组依据

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python分组依据

分两步完成。首先,创建字典。

>>> input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]>>> from collections import defaultdict>>> res = defaultdict(list)>>> for v, k in input: res[k].append(v)...

然后,将该字典转换为预期的格式。

>>> [{'type':k, 'items':v} for k,v in res.items()][{'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}]

使用itertools.groupby也可以,但是它要求输入首先被排序。

>>> sorted_input = sorted(input, key=itemgetter(1))>>> groups = groupby(sorted_input, key=itemgetter(1))>>> [{'type':k, 'items':[x[0] for x in v]} for k, v in groups][{'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}, {'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}]

请注意,这两个都不遵守键的原始顺序。如果需要保留订单,则需要一个OrderedDict。

>>> from collections import OrderedDict>>> res = OrderedDict()>>> for v, k in input:...   if k in res: res[k].append(v)...   else: res[k] = [v]... >>> [{'type':k, 'items':v} for k,v in res.items()][{'items': ['11013331', '9843236'], 'type': 'KAT'}, {'items': ['9085267', '11788544'], 'type': 'NOT'}, {'items': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 'type': 'ETH'}]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/653546.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号