2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

リスト中の要素ごとの出現回数を取得する

Last updated at Posted at 2019-06-28

「リスト中の要素ごとの出現回数を取得する」というのは、
具体的には、

["a", "b", "c", "c", "b", "c",]

から

{"a": 1, "b": 2, "c": 3,}

を得る操作を指すこととします。

これををいくつかの言語でやってみます。


Pythonの場合
import collections

list = ["a", "b", "c", "c", "b", "c",]

counter = collections.Counter(list)
print(dict(counter))
# -> {'a': 1, 'b': 2, 'c': 3}

参考:python - How to count the frequency of the elements in a list? - Stack Overflow

PHPの場合
$list = ["a", "b", "c", "c", "b", "c",];

$counts = array_count_values($list);
echo json_encode($counts) . PHP_EOL;
// -> {"a":1,"b":2,"c":3}

参考:PHP: array_count_values - Manual

Javaの場合
// import java.util.*;
// import java.util.stream.Collectors;
// import java.util.function.Function;

List<String> list = Arrays.asList("a", "b", "c", "c", "b", "c");
Map<String, Long> counts = list.stream()
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counts);
// -> {a=1, b=2, c=3}

参考:java - How to count the number of occurrences of an element in a List - Stack Overflow


おまけ

最初Laravelで以下のようにやってみたのですが、PHPはそのものズバリの標準関数がありましたね………
さすがPHP……

LaravelのCollectionを使う場合

$list = ["a", "b", "c", "c", "b", "c",];

$counts = collect($list)
    ->groupBy(null)
    ->map->count()
;

echo json_encode($counts) . PHP_EOL;
// -> {"a":1,"b":2,"c":3}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?