[英]Elixir Get Map containing maximum values of specific field
我是Elixir編程語言的初學者。
我有一個類似這樣的對象:
{
id: uuid,
created_at: DateTime.t,
updated_at: DateTime.t,
type: my_type
}
假設my_type
是my_type
~w[ABCD]
我想編寫一個函數,其中包含這些對象的列表並返回以下映射:
%{
A: 120,
B: 220,
C: 560,
D: 0,
any: 560
}
此處的值必須是每個my_type
+ any
其他updated_at
和created_at
列之間的最大差異( Timex.diff(updated_at, created_at, :seconds)
)。 在any
情況下,均不考慮my_type
並在列表中的所有對象中使用my_type
的最大值。
在Elixir中做這件事的最好方法是什么? 謝謝。
下面將按列表的類型對列表進行分組,然后計算每個組的最大差異,最后生成一個映射,其中包含每種類型作為鍵,最大差異作為值。
map = list
|> Enum.group_by(& &1.type)
|> Enum.map(fn {type, values} ->
max =
values
|> Enum.map(fn %{created_at: created_at, updated_at: updated_at} ->
# return the difference here
end)
|> Enum.max
{type, max}
end)
|> Map.new
這應該給你類似的東西:
%{
A: 120,
B: 220,
C: 560,
D: 0
}
您現在可以通過執行map |> Map.values |> Enum.max
來計算any
值。
我將其張貼在此處是為了格式化和多樣化。 @Dogbert的答案可能更合適,盡管這種方法可能更直接,更靈活。
list = [%{type: :a, v1: 10, v2: 20},
%{type: :a, v1: 10, v2: 30},
%{type: :b, v1: 10, v2: 20},
%{type: :c, v1: 10, v2: 20}]
kw = for %{type: t, v1: v1, v2: v2} <- list,
do: {t, v2 - v1}, into: []
#⇒ [a: 10, a: 20, b: 10, c: 10]
kw
|> Enum.sort_by(fn {_, v} -> v end, &>=/2)
|> Enum.uniq_by(fn {k, _} -> k end)
#⇒ [a: 20, b: 10, c: 10]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.