简体   繁体   中英

Erlang - Split a list into lists based on value

I am trying to split this list

List = [[<<"5">>, <<"54">>], [<<"00">>], [<<"35">>, <<"54">>, <<"45">>, <<"55">>], [<<"00">>],[ <<"5">>]]

into

List = [[<<"5">>, <<"54">>], [<<"35">>, <<"54">>, <<"45">>, <<"55">>], [<<"5">>]]

Basically based on the <<"00">>

What is the best BIF to go about this, I have some code, but its sloppy, and Im trying to learn.

Thanks

EDIT:

Tried the following, does not work

Done2 = lists:splitwith( [<<"00">>], Done1),

EDIT: This Line works!

7> lists:splitwith(fun(A) -> A == [<<"00">>] end, List).
{[],
 [[<<"5">>,<<"54">>],
  [<<"00">>],
  [<<"35">>,<<"54">>,<<"45">>,<<"55">>],
  [<<"00">>],
  [<<"5">>]]}

However I need something a little more complicated: like when the delim is [<<"00">>,<<"23">>]

9> List = [[<<"5">>,<<"54">>], [<<"00">>,<<"23">>], [<<"35">>,<<"54">>], [<<"5">
>], [<<"00">>, <<"23">>]].

[[<<"5">>,<<"54">>],
 [<<"00">>,<<"23">>],
 [<<"35">>,<<"54">>],
 [<<"5">>],
 [<<"00">>,<<"23">>]]

10> lists:splitwith(fun(A) -> A == [<<"00">>] end, List).
{[],
 [[<<"5">>,<<"54">>],
  [<<"00">>,<<"23">>],
  [<<"35">>,<<"54">>],
  [<<"5">>],
  [<<"00">>,<<"23">>]]}

11> lists:splitwith(fun(A) -> A == [<<"00">>,<<"23">>] end, List).
{[],
 [[<<"5">>,<<"54">>],
  [<<"00">>,<<"23">>],
  [<<"35">>,<<"54">>],
  [<<"5">>],
  [<<"00">>,<<"23">>]]}
12>

No luck there

I am not sure if I understood your requirements correctly. Here is a possible solution. It will split the list on any delimiter like [<<"00">> | _ ].

1> List = [[<<"5">>, <<"54">>], [<<"00">>], [<<"35">>, <<"54">>, <<"45">>, <<"55">>], [<<"00">>, <<"23">> ],[ <<"5">>]].
[[<<"5">>,<<"54">>],
 [<<"00">>],
 [<<"35">>,<<"54">>,<<"45">>,<<"55">>],
 [<<"00">>,<<"23">>],
 [<<"5">>]]
2> List2 =  [ X || X <- List, case X of [ <<"00">> | _ ] -> false; _ -> true end].                                      
[[<<"5">>,<<"54">>],
 [<<"35">>,<<"54">>,<<"45">>,<<"55">>],
 [<<"5">>]]

1> List = [[<<"5">>,<<"54">>], [<<"00">>,<<"23">>], [<<"35">>,<<"54">>], [<<"5">>], [<<"00">>, <<"23">>]]. [[<<"5">>,<<"54">>], [<<"00">>,<<"23">>], [<<"35">>,<<"54">>], [<<"5">>], [<<"00">>,<<"23">>]]

2> Delimiter = [<<"00">>,<<"23">>].
[<<"00">>,<<"23">>]

3> lists:filter(fun(L) -> L /= Delimiter end, List).
[[<<"5">>,<<"54">>],[<<"35">>,<<"54">>],[<<"5">>]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM