【问题标题】:Check if key is below a threshold [closed]检查密钥是否低于阈值[关闭]
【发布时间】:2020-11-28 18:25:41
【问题描述】:

给定一个键和值,当它

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

有没有更简单的方法?

【问题讨论】:

  • 这不会做那种事情。您不会将逗号分隔的赋值字符串转换为实数,因此您无法比较其中的任何内容
  • 如何转换?是我的问题

标签: json python-3.x dictionary


【解决方案1】:

需要进一步预处理才能算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

【讨论】:

    猜你喜欢
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    相关资源
    最近更新 更多