检查钥匙是否低于阈值



GIven一个键和值,当它<50,在以下情况下计数为2(30和40(

import json
# some JSON:
x = '{ "name":"a=30,b=50,a=40,b=44"}'
# parse x:
d = []
c = []
y = json.loads(x).values()
for i in y:
print((i.replace("=",":")))
## Check for threshold value

有更简单的方法吗?

在计数a<50:之前,需要进行进一步的预处理

import json
# some JSON:
x = '{ "name":"a=30,b=50,a=40,b=44,a=99"}'
# parse x:
d = []
c = []
y = json.loads(x).values()
for i in y:
# split the string at , to get single assignments
for assignment in i.split(","):
inner = {}
# convert assignmets to key and intvalue 
a,b = assignment.split("=")
b = int(b) # this will crash if your input is bad
inner[a] = int(b)
d.append(inner)
a_under_50 = [p.get("a",99) < 50 for p in d] # list of True/False
print(d)
# True == 1, False == 0 - if you sum them you get your output
print(sum(a_under_50))

输出:

[{'a': 30}, {'b': 50}, {'a': 40}, {'b': 44}, {'a': 99}]
2

最新更新