【问题标题】:Is there a Javascript function similar to the Python Counter function?有没有类似于 Python Counter 函数的 Javascript 函数?
【发布时间】:2014-10-11 23:17:43
【问题描述】:

我正在尝试将我的程序从 Python 更改为 Javascript,我想知道 Python 中的集合模块中是否有类似 Counter 函数的 JS 函数。

计数器的语法

from collection import Counter
list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a']
counter = Counter(list)
print counter

输出

Counter({'a':5, 'b':3, 'c':2})

【问题讨论】:

标签: javascript python


【解决方案1】:

DIY JavaScript 解决方案:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];

function Counter(array) {
  var count = {};
  array.forEach(val => count[val] = (count[val] || 0) + 1);
  return count;
}

console.log(Counter(list));

JSFiddle example

更新:

使用 构造函数 函数的替代方案:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];

function Counter(array) {
  array.forEach(val => this[val] = (this[val] || 0) + 1);
}

console.log(new Counter(list));

JSFiddle example

【讨论】:

  • 谢谢!我添加了一个使用构造函数和new 关键字的替代方法。
  • 超级酷!
【解决方案2】:

你可以使用 Lo-Dash 的countBy 函数:

var list = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];
console.log(_.countBy(list));

JSFiddle example

【讨论】:

  • console.log(_.countBy([4,6,5,8,8,9,7,8])) 产生"_ is not defined"
  • 你需要包含 lodash 库
【解决方案3】:

我知道我迟到了,但如果有人在 2020 年看到这个,你可以使用 reduce 来做,例如:

const counter = (list) => {
  return list.reduce(
    (prev, curr) => ({
      ...prev,
      [curr]: 1 + (prev[curr] || 0),
    }),
    {}
  );
};

console.log(counter([1, 2, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 1, 0]));
// output -> { '0': 1, '1': 6, '2': 2, '3': 1, '4': 1, '5': 1, '6': 1, '7': 1 }

带有回调函数和上下文绑定的更高级示例

const data = [1, 2, 3, 4, 5];

const counter = (list, fun, context) => {
  fun = context ? fun.bind(context) : fun;
  return list.reduce((prev, curr) => {
    const key = fun(curr);
    return {
      ...prev,
      [key]: 1 + (prev[key] || 0),
    };
  }, {});
};


console.log(counter(data, (num) => (num % 2 == 0 ? 'even' : 'odd')));
// output -> { odd: 3, even: 2 }

【讨论】:

    【解决方案4】:

    还有pycollections.js,适用于Node和客户端JS。

    例子:

    var collections = require('pycollections');
    var counter = new collections.Counter([true, true, 'true', 1, 1, 1]);
    counter.mostCommon(); // logs [[1, 3], [true, 2], ['true', 1]] 
    

    【讨论】:

      【解决方案5】:

      对于那些想要纯 JavaScript 解决方案的人:

      function countBy (data, keyGetter) {
        var keyResolver = {
          'function': function (d) { return keyGetter(d); },
          'string': function(d) { return d[keyGetter]; },
          'undefined': function (d) { return d; }
        };
      
        var result = {};
      
        data.forEach(function (d) {
          var keyGetterType = typeof keyGetter;
          var key = keyResolver[keyGetterType](d);
      
          if (result.hasOwnProperty(key)) {
            result[key] += 1;
          } else {
            result[key] = 1;
          }
        });
      
        return result;
      }
      

      因此:

      list1 = ['a', 'b', 'c', 'b', 'a', 'b', 'c', 'a', 'a', 'a'];
      console.log(countBy(list1));  // {'a':5, 'b':3, 'c':2}
      
      list2 = ['abc', 'aa', 'b3', 'abcd', 'cd'];
      console.log(countBy(list2, 'length'));  // {2: 3, 3: 1, 4: 1}
      
      list3 = [1.2, 7.8, 1.9];
      console.log(countBy(list3, Math.floor));  // {1: 2, 7: 1}
      

      【讨论】:

        【解决方案6】:

        这是一个简单易读的解决方案:

         const word1 = "tangram"
            const dict1 = {}
            for (let char of word1){
             console.log(char)
             if (dict1[char]){
               dict1[char] += 1
               }else{
             dict1[char]= 1
             }
            }

        【讨论】:

          【解决方案7】:

          这是我的显式函数调用解决方案

          let list = [4, 6, 5, 3, 3, 1];
          
          function counter(list) {
          
            let count = function(n) {
              let cnt = 0;
              for (let v of list) {
                if (v === n) cnt++
              }
              return cnt
            }
          
            let [...listSet] = new Set(list);
            let cntr = {};
            for (let v of listSet) {
              cntr[v] = count(v)
            }
            return cntr
          
          }
          
          console.log(counter(list))
          

          【讨论】:

            【解决方案8】:

            另一个版本->

            s = "naman";
            
            const counter = (s, sMap = {}) => {
              [...s].map((el) => {
                sMap[el] = sMap[el] ? sMap[el] + 1 : 1;
              });
              return sMap;
            };
            
            const res = counter(s);
            console.log(`res`, res);
            
            

            【讨论】:

              【解决方案9】:

              在 Python 中,Counter 也有 addupdate 方法,它们使用得相当普遍。所以更好的解决方案是:

              function Counter(array) {
                  this.add = (val) => {
                      this[val] = (this[val] || 0) + 1;
                  };
                  this.update = (array) => {
                      array.forEach((val) => this.add(val));
                  };
                  this.update(array);
              }
              
              // Example usage
              let myCounter = new Counter([1, 2, 2])
              myCounter.update([3, 3, 3])
              myCounter.add(4)
              console.log(myCounter)

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2019-06-04
                • 1970-01-01
                • 2021-09-17
                • 2012-01-06
                • 2020-11-04
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多