2017-05-07 63 views
1

什麼在藥劑中最優雅的方式來改造藥劑枚舉,過濾器和組

[["A","B","foo"],["A","B","bar"],["A","B","baz"],["C","D","foobar"],["C","D","bla"],["E","F","blabla"]] 

到:

[["A","B","foo","bar","baz"],["C","D","foobar","bla"],["E","F","blabla"]] 

基本上我想遍歷輸入列表和組由前兩個元素。

回答

2

我最好組由Enum.take(2),然後flat_map每組Enum.drop(2)

[["A","B","foo"],["A","B","bar"],["A","B","baz"],["C","D","foobar"],["C","D","bla"],["E","F","blabla"]] 
|> Enum.group_by(&Enum.take(&1, 2)) 
|> Enum.map(fn {key, value} -> 
    key ++ Enum.flat_map(value, &Enum.drop(&1, 2)) 
end) 
|> IO.inspect 

輸出:

[["A", "B", "foo", "bar", "baz"], ["C", "D", "foobar", "bla"], 
["E", "F", "blabla"]] 

注意,這也將工作,如果在輸入列表中的任何項目都有> 3要素;在這種情況下,它會只是Concat的他們:

[["A","B","foo","z","zz"],["A","B","bar"],["A","B","baz"],["C","D","foobar"],["C","D","bla"],["E","F","blabla"]] 

將輸出:

[["A", "B", "foo", "z", "zz", "bar", "baz"], ["C", "D", "foobar", "bla"], 
["E", "F", "blabla"]] 
+0

是的,這就是exactely我想要的!謝謝! – ctp