我想根据我的规则对某些数据进行分类,这些规则并不完全符合我的规则。
group = ((1, ["zt"]), (2, ["xjt"]), (3, ["ppt"]), (4, ["dpt"]), (5, ["sxb"]), (6, ["tmzt"]))
indata = [(1001,"zt_1"), (1002,"zt_2"), (1021,"tmzt_1"),(1023,"xjt_1"), (1244,"xjt_2")]
我希望按规则分组(组)
outdata = [(1, 1001,"zt_1", 1), (1, 1002,"zt_2", 2), (6, 1021,"tmzt_1", 1),(2, 1023,"xjt_1", 1), (2, 1244,"xjt_2", 2)]
outdata包含(组ID,indata id,indata名称,组内部排序)但并非所有数据都符合我的组规则。
输出也可以像一个字典
[{"group_id": 1, "image_id": 1001, "name": "zt_1", "sort_order": 1}, ...]
集团是独一无二的
您可以通过创建中间字典来更轻松地解决这个问题,该字典可用于检查应在结果中保留哪些值。
group = ((1, ["zt"]), (2, ["xjt"]), (3, ["ppt"]), (4, ["dpt"]), (5, ["sxb"]), (6, ["tmzt"]))
indata = [(1001,"zt_1"), (1002,"zt_2"), (1021,"tmzt_1"),(1023,"xjt_1"), (1244,"xjt_2")]
group_dict = {tup[1][0]: tup[0] for tup in group}
#Output:
{'zt': 1, 'xjt': 2, 'ppt': 3, 'dpt': 4, 'sxb': 5, 'tmzt': 6}
result = []
for tup in indata:
key, val = tup[1].split("_")
if key in group_dict:
result.append((group_dict[key], *tup, int(val)))
print(result)
#Output:
[(1, 1001, 'zt_1', 1),
(1, 1002, 'zt_2', 2),
(6, 1021, 'tmzt_1', 1),
(2, 1023, 'xjt_1', 1),
(2, 1244, 'xjt_2', 2)]