Let's say I have the following list:
list =
{{"Text", "hello", "a"}, {"Text", " world", "a"}, {"TextElement", "line", "a"},
{"TextElement", "line", "a"}, {"Text", "!", "b"}, {"Text", "ok", "c"}}
I want to to combine elements in list
with the same first and last item (Eg: "Text"
and "a"
), but I do not want to combine elements which meet some condition. For this example, I do not want to combine elements whose first item is "TextElement"
. Thus, here is the expected output:
{{{"Text", "hello", "a"}, {"Text", " world", "a"}},
{{"TextElement", "line", "a"}},
{{"TextElement", "line", "a"}},
{{"Text", "!", "b"}},
{{"Text", "ok", "c"}}}
Outline (for readability): {1, 2, 3, 4, 5, 6}
→ {{1, 2}, {3}, {4}, {5}, {6}}
I've tried the following code:
SplitBy[list, First[#] && Last[#] && ! (#[[1]] == "TextElement" && #[[2]] == "line") &]
It seemed to work at first, but fails the test above, as it combines the two "TextElement"
elements. After looking at how the test function is evaluated, I can see why it doesn't work. How do I elegantly achieve the output above without resorting to loops?
Gather
orGatherBy
would be more appropriate. $\endgroup$