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$ Commented Dec 11, 2018 at 23:35
  • $\begingroup$ Take a look at DeleteDuplicatesBy. $\endgroup$ Commented 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$ Commented 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$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.