Wolfram: List. Same Items Counts, Tally, Group

By Xah Lee. Date: . Last updated: .

Tally. Group a List into Sublists Same Items, with Count

Tally[list]
  • Count occurrence of same items, for all items.
  • Return a list of the form {{e1, count1},{e2, count2},etc}
Tally[{a,b,c,a,a}]
(* {{a, 3}, {b, 1}, {c, 1}} *)
Tally[list, testF]
  • Count occurrence of similar items, for all items.
  • similarity is determined by testF[a,b]. if return true, it is considered similar.
  • Return a list.
  • Each element is the first element and its corresponding count.
Tally[{{1,1},{1,2},{1,1,1}, {Sin[3], Cos[4]}},
Function[{a,b}, Length[a] === Length[b]
]
]
(* {{{1, 1}, 3}, {{1, 1, 1}, 1}} *)
(* similar considered as distance of vectors *)
Tally[{{1,0},{0,1},{1,2},{0,1,0}, {Sin[3], Cos[3]}},
Function[{a,b}, Norm[N[a]] === Norm[N[b]]]
]
(* {{{1, 0}, 4}, {{1, 2}, 1}} *)

Count Same Elements

Counts[list]
  • Count occurrence of same items, for all items.
  • Return an Association.
  • Each pair is the element and its corresponding count.
Counts[{a,b,c,a,a}]
(* <|a -> 3, b -> 1, c -> 1|> *)

Count Similar Elements

CountsBy[list, f]
  • Count occurrence of similar items, for all items.
  • Similarity is defined by a characteristic function f. If f[a] === f[b] , then a and b are considered same.
  • Return an Association.
  • Each pair, the key is f[ele] and its count of occurrence.
CountsBy[{1,2,3,4,5}, Function[{x}, Mod[ x, 2]]]
(* <|1 -> 3, 0 -> 2|> *)

Group Similar Elements

GroupBy[ list, f ]
  • Return an Association
  • Group the list by a characteristic function f.

For example, given a list of integers, you want to group by even numbers. So your characteristic function is EvenQ. The result association has two keys, True and False, their values are the corresponding elements in the list.

GroupBy[ {3,4,5}, EvenQ ]
(* <|False -> {3, 5}, True -> {4}|> *)
xx = {1,2,3,4,5,6,7,8,9,10};
GroupBy[ xx, Function[{x}, Mod[ x, 3 ]] ]
(* <|1 -> {1, 4, 7, 10}, 2 -> {2, 5, 8}, 0 -> {3, 6, 9}|> *)
xx = {{1,2},{4,5,6},{3,4},{aa,bb,cc},{7,8,9,10}};
GroupBy[ xx, Length ]
(* <|2 -> {{1, 2}, {3, 4}}, 3 -> {{4, 5, 6}, {aa, bb, cc}}, 4 -> {{7, 8, 9, 10}}|> *)
GroupBy[ list, fg ]

same as GroupBy[ list, f ], but apply g to the original list element in the result key's values.

GroupBy[ {3,4,5}, EvenQ -> g]
(* <|False -> {g[3], g[5]}, True -> {g[4]}|> *)
xx = {1,2,3,4,5,6,7,8,9,10};
GroupBy[ xx, Function[{x}, Mod[ x, 3 ]] -> g ]
(* <|1 -> {g[1], g[4], g[7], g[10]}, 2 -> {g[2], g[5], g[8]}, 0 -> {g[3], g[6], g[9]}|> *)
xx = {{1,2},{4,5,6},{3,4},{aa,bb,cc},{7,8,9,10}};
GroupBy[ xx, Length -> ff]
(* <|2 -> {ff[{1, 2}], ff[{3, 4}]}, 3 -> {ff[{4, 5, 6}], ff[{aa, bb, cc}]}, 4 -> {ff[{7, 8, 9, 10}]}|> *)

Get Indexes of Same Elements

PositionIndex[list]

Return an Association. Each pair, the key is ele and value is list of their indexes.

PositionIndex[{a,b,c,a,a}]
(* <|a -> {1, 4, 5}, b -> {2}, c -> {3}|> *)

Wolfram. List Operations, and Loop, Iteration, Recursion