我有一个很大的JSON对象。其中一部分是:
data = [
{
'make': 'dacia',
'model': 'x',
'version': 'A',
'typ': 'sedan',
'infos': [
{'id': 1, 'name': 'steering wheel problems'},
{'id': 32, 'name': 'ABS errors'}
]
},
{
'make': 'nissan',
'model': 'z',
'version': 'B',
'typ': 'coupe',
'infos': [
{'id': 3,'name': 'throttle problems'},
{'id': 56, 'name': 'broken handbreak'},
{'id': 11, ;'name': 'missing seatbelts'}
]
}
]
我创建了一个我感兴趣的信息列表,这些信息可能出现在我的JSON中:
make = ['ford', 'fiat', 'nissan', 'suzuki', 'dacia']
model = ['x', 'y', 'z']
version = ['A', 'B', 'C']
typ = ['sedan', 'coupe', 'van', 'kombi']
现在我需要迭代整个JSONdata
,并计算某些信息组合出现的次数,因此我创建了一个代码:
tab = []
s = 0
for ma in make:
for mo in model:
for ve in version:
for ty in typ:
s = sum([1 for k in data if k['make] == ma and k['model] == mo and k['version'] == ve and k['typ'] == ty)
if s != 0:
total.append({'make': i, 'model': j, 'version': i, 'typ': j, 'sum': s})
我面临的问题是,我意识到这不是最佳方式。有没有办法加速和改进这段代码
使用
正确的数据(发布时有错误,即伪“;”)
计数组合
您可以将键用作元组(4元组)并实现自己的计数器
然后,您可以从该
res
中筛选不需要的组合。您可以使用if
来检查4元组是否来自需要筛选的组合集。所以让这个线性化编辑,也可以使用
collections.Counter
如果您有一个名为
combinations
的组合集,那么添加过滤器可能类似于。Python 3.8+相关问题 更多 >
编程相关推荐