4
$\begingroup$

I have a list:

lis = {{"b","x","d"},{"a","z","b"},{"a","x","b"},{"a","x","c"},{"b","z","d"}}

Certain consecutive elements of this list will have identical first and last members (in this example, "a" and "b" in lis[[2]] and lis[[3]]) and I would like to delete the element that has "x" as its middle element, to give:

res = {{"b","x","d"},{"a","z","b"},{"a","x","c"},{"b","z","d"}}

It seems like a job for SequenceCases, but am having no luck.

$\endgroup$
3
  • 2
    $\begingroup$ elements 1 and 5 also have identical first and last members...Shouldn't you erase the first element, too? $\endgroup$
    – ZaMoC
    Dec 11, 2018 at 23:35
  • $\begingroup$ Take a look at DeleteDuplicatesBy. $\endgroup$
    – Kuba
    Dec 11, 2018 at 23:47
  • $\begingroup$ Another approach could be to start with Split[lis, #1[[1]] == #2[[1]] && #1[[3]] == #2[[3]] &] to group the consecutive elements. $\endgroup$ Dec 11, 2018 at 23:53

2 Answers 2

9
$\begingroup$
SequenceReplace[lis, {OrderlessPatternSequence[{a_, "x", c_}, {a_, b_, c_}]} :> {a, b, c}]

{{"b", "x", "d"}, {"a", "z", "b"}, {"a", "x", "c"}, {"b", "z", "d"}}

$\endgroup$
2
$\begingroup$

One approach is to look at the differences between adjacent elements, find those which equal {0,0,x_}, and remove them from the list.

lis[[Complement[Range[Length[lis]],Flatten@Position[Differences[lis], {0, 0, x_}]]]]

{{"b", "x", "d"}, {"a", "z", "b"}, {"a", "x", "c"}, {"b", "z", "d"}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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