Json计数元素取决于另一个使用Python的值

时间:2016-01-30 01:35:28

标签: python json

我有一个看起来像这样的JSON对象:

[{'key1': 'yes', 'key2': 'yes', 'key3': 'yes'},
 {'key1': 'yes', 'key2': 'no', 'key3': 'yes'},
 {'key1': 'yes', 'key2': 'null', 'key3': 'yes'}]

当Key2的值不是,我试图计算Key1的出现次数,我可以使用它来按Key2中值Yes的出现对Key1进行排名。

2 个答案:

答案 0 :(得分:2)

您可以使用sum()

>>> l = [
    {"key1": "yes", "key2": "yes", "key3": "yes"}, 
    {"key1": "yes", "key2": "no", "key3": "yes"}, 
    {"key1": "yes", "key2": "null", "key3": "yes"}
]
>>> sum(item["key2"] != "yes" for item in l)
2

答案 1 :(得分:0)

我有另一个答案,它由'filter'和'len'实现:

const Task = require('data.task'); // folktale
const Either = require('data.either');

// eitherYayNay :: Bool → Either String String
const eitherYayNay = bool =>
  bool ? Either.Right('yay') : Either.Left('nay');

// theTask :: Bool → Task Either a b
const theTask = yn =>
  new Task((reject, resolve) => {
    resolve(eitherYayNay(yn));
    // reject();
  });

// niceTask :: Bool → Task a b
// ???

// the desired result...
niceTask(something).fork(
  err => { 
    // err could be the left value of the Task, or of the Either
  },
  val => { 
    console.log(val); // a string, not an Either
  }
);

l = [ {"key1": "yes", "key2": "yes", "key3": "yes"}, {"key1": "yes", "key2": "no", "key3": "yes"}, {"key1": "yes", "key2": "null", "key3": "yes"} ] f = filter(lambda x: x['key2']!='yes', l) print f print len(f) 输出过滤结果。 print f将进一步输出过滤结果的编号。

print len(f)
相关问题