我想使用python在JSON文件中找到最大值(因此它将是字典)。 我的JSON具有以下形状:
[{
"probability": 0.623514056,
"boundingBox": { "left": 36, "top": 1, "width": 403, "height": 95 }
},
{
"probability": 0.850905955,
"boundingBox": { "left": 42, "top": 200, "width": 412, "height": 90 }
},
{
"probability": 0.308903724,
"boundingBox": { "left": 79, "top": 309, "width": 690, "height": 125 }
}]
我想找到最大和最小宽度。并且执行2个“ for”将花费很多时间(因为JSON大于此处显示的内容)。有最佳的方法吗?像max( something )
所以我想要的输出是:
Max Width: 690
Min Width: 403
答案 0 :(得分:2)
最干净的解决方案可能是:
widths = [d['boundingBox']['width'] for d in json_file]
min_value = min(widths)
max_value = max(widths)
但是,min
和max
仅在后台使用循环,您提到的循环可能很慢。首先测试上述解决方案,如果这对于您的需求而言太慢了,您可以将循环组合成一个循环:
min_value, max_value = float('inf'), float('-inf')
for d in json_file:
value = d['boundingBox']['width']
if value < min_value:
min_value = value
if value > max_value:
max_value = value
编辑:性能差异可以忽略不计。和第一个一起去。
Python 3.7.2 (default, Dec 29 2018, 06:19:36)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> test = """\
... values = [v for v in x]
... min_value = min(values)
... max_value = max(values)
... """
>>> timeit.timeit(stmt=test, number=10000, setup="""import numpy as np; x = np.random.rand(10000)""")
7.404742785263807
>>> test2 = """\
... min_value, max_value = float('inf'), float('-inf')
... for v in x:
... value = v
... if value < min_value:
... min_value = value
... if value > max_value:
... max_value = value
... """
>>> timeit.timeit(stmt=test2, number=10000, setup="""import numpy as np; x = np.random.rand(10000)""")
7.252437709830701
答案 1 :(得分:1)
这很容易做到:
max_width = max(d["boundingBox"]["width"] for d in dicts)
min_width = min(d["boundingBox"]["height"] for d in dicts)
答案 2 :(得分:0)
我会使用lambda函数
max(data, key=lambda d: d['boundingBox']['width'])
min(data, key=lambda d: d['boundingBox']['width'])