Mathematica Asked on June 6, 2021
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.
Union[lis, SameTest -> (And[#[[2]] == "xx", #[[{1, 3}]] == #2[[{1, 3}]]] &)]
{{"a", "23", "b"}, {"c", "18", "d"}, {"w", "xx", "z"}}
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"}}
Correct answer by kglr on June 6, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP