【问题标题】:Python: if abc in j['category']Python:如果 j['category'] 中的 abc
【发布时间】:2015-02-10 02:24:35
【问题描述】:

给定一个如下所示的 JSON 文件:

"foobar": [
    {
        "a": "true",
        "b": 1,
        "c": 1234,
        "d": 9,
        "e": "red"
    },
    {
        "a": "false",
        "b": 2,
        "c": 2345,
        "d": 7,
        "e": "green"
    },
    {
        "a": "whocares",
        "b": 3,
        "c": 3456,
        "d": 5,
        "e": "blue"
    }
]

是否可以在没有循环的情况下检查其中任何中是否存在“蓝色”?

import simplejson
j = json.loads(superfile().text)
if "blue" in j['foobar'][ANYONE]['e']

【问题讨论】:

  • 你为什么要避免循环?列表太大了吗?
  • ...any?
  • @RafaelBarros 不一定。我只是想让事情变得简单。
  • @jonrsharpe 你可能想提供一个例子。 any 通常只检查列表元素是否为真。在这种情况下,列表元素是 dicts,问题是对于每个 dict 元素找出其中一个 dict 值是否为“蓝色”。
  • @Evert Cyber​​ 为我做了这件事!

标签: python json list python-2.7


【解决方案1】:

正如@jonrsharpe 提到的,您最好的选择可能是使用any,例如

if any('blue' in i['e'] for i in j['foobar'])

或者

if any('blue' == i['e'] for i in j['foobar'])

【讨论】:

  • blue 是一个变量时,这也会捕获“bl”。这可以避免吗?
猜你喜欢
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多