Python:根据条件获取出现次数

时间:2018-09-20 18:28:26

标签: python

如果我有一个整数列表和一个返回某些枚举类型的函数getErrorType(int),那么用哪种Python方式来获得一个字典,其中的键是枚举类型,而值是数组中有多少个值的计数返回该错误类型?

示例: arr = [1, 2, 3] getErrorType(1) returns EXCEPTION getErrorType(2) returns MALFORMED_DATA getErrorType(3) returns EXCEPTION

我希望能够获得:{EXCEPTION: 2, MALFORMED_DATA: 1}

5 个答案:

答案 0 :(得分:0)

我会用dict理解

d={getErrorType(a):a for a in arr}

编辑:

确定要获得OP所说的计数,我会做这样的事情

d={x: [getErrorType(a) for a in arr].count(x) for x in set([getErrorType(a) for a in arr])}

尽管这可能会使阅读变得难以理解,成为pythonic /////

答案 1 :(得分:0)

data = {}

for a in arr:
    error_type = getErrorType(a)
    if error_type in data:
        data[error_type] += 1
    else:
        data[error_type] = 1

答案 2 :(得分:0)

不要认为有一种使用dict理解来保持计数的有效方法。

我可能只会使用普通字典或defaultdict的迭代方法

from collections import defaultdict
d = defaultdict(int)
for num in arr: d[getErrorType(num)] += 1

答案 3 :(得分:0)

制作一个通用函数只是为了模拟您可以将整个arr传递到函数中,然后可以在新列表上使用.count并将结果形成二进阶数字

def getErrorType(a):
    return ['Ex' if i % 2 else 'Mal' for i in a ]

arr = [1, 2, 3]
lista = getErrorType(arr)
dicta = {i: lista.count(i) for i in lista}
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 helping.py 
{'Ex': 2, 'Mal': 1}

我不同意通过遍历+= 1的每一项来创建似乎效率不高的字典,我支持

答案 4 :(得分:0)

结合了上面的一些解决方案

let anArrayOfUniqueNumbers = [];

let numberGenerator = function(arr) {
  if (arr.length >= 10) return;
  let newNumber = Math.floor(Math.random() * 10 + 1);
  if (arr.indexOf(newNumber) < 0) {
    arr.push(newNumber);
  }
  numberGenerator(arr);
};

numberGenerator(anArrayOfUniqueNumbers);