我有一个包含多种类型的字典的数组,例如:
arr = [
{'type': 'employee.update', ...},
{'type': 'job.started', ...},
{'type': 'meeting.xpto', ...}
...
]
如何按类型前缀拆分“主”数组?是否有必要为每个前缀迭代整个数组?
employess_actions = list(filter(lambda x: x['type'].startswith('employee.'), arr))
job_actions = list(filter(lambda x: x['type'].startswith('job.'), arr))
meeting_actions = list(filter(lambda x: x['type'].startswith('meeting.'), arr))
有没有什么有效的方法可以实现它?或者Pythonic方式。
最佳答案
您可以使用(默认)字典按前缀收集元素:
from collections import defaultdict
result = defaultdict(list)
for o in arr:
result[o["type"][:o["type"].index(".")]].append(o)
这当然假设所有这些类型都有一个“.”。在他们之中。
例如,如果:
arr = [
{"type": "employee.update"},
{"type": "job.started"},
{"type": "meeting.xpto"},
{"type": "job.ended"}
]
那么得到的结果
是
{
"employee": [{"type": "employee.update"}],
"job": [{"type": "job.started"}, {"type": "job.ended"}],
"meeting": [{"type": "meeting.xpto"}]
}
关于python - 如何根据属性值将数组拆分为另一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62742026/