【问题标题】:perl: How to I count multiple values in hash into a new hash?perl:如何将哈希中的多个值计算为新的哈希?
【发布时间】:2018-04-17 21:26:13
【问题描述】:

我当前的哈希:

%hash = (
  "foo",
   [
     "apple",
     "orange",
     "apple",
     "apple"
  ],
  "bob",
  [
    "apple",
    "orange",
  ],
);

我如何获得这个输出?

%hash2 = (
  apple  => 4,
  orange => 2,
);

【问题讨论】:

    标签: perl


    【解决方案1】:
    my %counts;
    for (values(%hash)) {  # Iterate over the values of the hash, the references to the arrays.
       for (@$_) {         # Iterate over the values of the referenced array.
          ++$counts{$_};
       }
    }
    

    my %counts;
    ++$counts{$_} for map @$_, values %hash;
    

    【讨论】:

    • 在 for 循环中命名迭代器变量。
    • 用一个无意义的名字替换另一个没有帮助。
    • 这就是为什么你应该为你的变量和函数选择有意义的名字。
    猜你喜欢
    • 2010-10-20
    • 2015-08-01
    • 1970-01-01
    • 2012-11-11
    • 2016-06-23
    • 2016-07-22
    • 2013-06-06
    • 2011-04-20
    相关资源
    最近更新 更多