我有下面的字典输入列表
inpdata = {"cat": [{"categories": [{"cid": 27}, {"cid": 66}, {"cid": 29}], "id": 20},
{"categories": [{"cid": 66}], "id": 21},
{"categories": [{"cid": 66}, {"cid": 27}], "id": 22},
{"categories": [{"cid": 66}, {"cid": 27}], "id": 23},
{"categories": [{"cid": 66}, {"cid": 29}, {"cid": 27}], "id": 24}]};
我试图获取每个cid的id计数以及id值,我使用下面的代码 -
allcategories = set( sec['cid'] for record in inpdata['cat'] for sec in record['categories'] )
summarize = lambda record: record['id']
fs_cat = [
{
'cat':cid,
'count':len(matches),
'ids':[ summarize( match ) for match in matches ]
}
for cid in allcategories
for matches in [[
record for record in inpdata['cat'] if cid in [ sec['cid'] for sec in record['categories'] ]
]]
]
print(fs_cat)
这将输出显示为 -
[{'cat': 66, 'count': 5, 'ids': [20, 21, 22, 23, 24]},
{'cat': 27, 'count': 4, 'ids': [20, 22, 23, 24]},
{'cat': 29, 'count': 2, 'ids': [20, 24]}
]
但我怎样才能得到类别组合{66,27,29}?
我尝试使用以下方法获取此输入的组合 - 它提供了列表中项目的组合
allcategories = {66,27,29}
for subset in itertools.chain.from_iterable(itertools.combinations(allcategories, n) for n in range(len(allcategories) + 1)):
print(subset)
但我无法弄清楚如何使用这种方法从'inpdata'
获取类别{66,27,29}的结果如下所示result=[{'cat': '66', 'count': 5, 'ids': [20, 21, 22, 23, 24]},
{'cat': '27', 'count': 4, 'ids': [20, 22, 23, 24]},
{'cat': '29', 'count': 2, 'ids': [20, 24]},
{'cat': '66&27', 'count': 4, 'ids': [20, 22, 23, 24]},
{'cat': '66&29', 'count': 2, 'ids': [20, 24]},
{'cat': '27&29', 'count': 2, 'ids': [20, 24]},
{'cat': '66&27&29', 'count': 2, 'ids': [20, 24]}
]
您能否就我如何实现这一目标提出建议?
答案 0 :(得分:2)
itertools.combinations(1)
,itertools.combinations(2)
,......最高itertools.combinations(n)
会为您提供fs_cat
(其中,n = len(fs_cat)
)
import itertools
import operator
from functools import reduce
fs_cat = [
{'cat': 66, 'count': 5, 'ids': [20, 21, 22, 23, 24]},
{'cat': 27, 'count': 4, 'ids': [20, 22, 23, 24]},
{'cat': 29, 'count': 2, 'ids': [20, 24]},
]
result = []
for n in range(1, len(fs_cat) + 1): # 1, 2, ..., len(fs_cat)
for xs in itertools.combinations(fs_cat, n):
cat = '&'.join(map(str, sorted(x['cat'] for x in xs)))
ids = sorted(reduce(operator.and_, (set(x['ids']) for x in xs)))
result.append({'cat': cat, 'count': len(ids), 'ids': ids})
>>> result
[{'cat': '66', 'count': 5, 'ids': [20, 21, 22, 23, 24]},
{'cat': '27', 'count': 4, 'ids': [20, 22, 23, 24]},
{'cat': '29', 'count': 2, 'ids': [20, 24]},
{'cat': '27&66', 'count': 4, 'ids': [20, 22, 23, 24]},
{'cat': '29&66', 'count': 2, 'ids': [20, 24]},
{'cat': '27&29', 'count': 2, 'ids': [20, 24]},
{'cat': '27&29&66', 'count': 2, 'ids': [20, 24]}]