5
$\begingroup$

I have a list:

lis = {{"a", "xx", "b"}, {"c", "18", "d"}, {"a", "23", "b"}, {"w", "xx", "z"}}

I would like to obtain:

res = {{"c", 18, "d"}, {"a", "23", "b"}, {"w", "xx", "z"}}

where items are dropped from lis if their middle sub-element is "xx" and another element in lis contains the same first and last sub-elements and has digit characters in its middle sub-element. Sorting by lis[[1]] puts the two almost identical items next to each other, but I'm not sure how to use DeleteCases here.

$\endgroup$
7
$\begingroup$

Union:

Union[lis, SameTest -> (And[#[[2]] == "xx", #[[{1, 3}]] == #2[[{1, 3}]]] &)]

{{"a", "23", "b"}, {"c", "18", "d"}, {"w", "xx", "z"}}

DeleteCases:

cond = And[#[[2]] == "xx" , 
  MatchQ[#[[{1, 3}]], Alternatives @@ Complement[lis, {#}][[All, {1, 3}]]]] &;
DeleteCases[lis, _?cond]

{{"c", "18", "d"}, {"a", "23", "b"}, {"w", "xx", "z"}}

A combination of GatherBy and DeleteCases:

Join @@ If[Length @ # > 1, DeleteCases[#, {_, "xx", _}], #] & /@ 
 GatherBy[lis, #[[{1, 3}]] &]

{{"a", "23", "b"}, {"c", "18", "d"}, {"w", "xx", "z"}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.