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$
  • 2
    $\begingroup$ elements 1 and 5 also have identical first and last members...Shouldn't you erase the first element, too? $\endgroup$ – J42161217 Dec 11 '18 at 23:35
  • $\begingroup$ Take a look at DeleteDuplicatesBy. $\endgroup$ – Kuba Dec 11 '18 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$ – That Gravity Guy Dec 11 '18 at 23:53
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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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