I have a list:

lis = {{a},{1,2},{b},{3},{c,z},{d,e,f},{4}}

I would like to join adjacent members of this list when both are not integers (or lists of integers), producing:

res = {{a},{1,2},{b},{3},{c,z,d,e,f},{4}}

Testing all members of lis with Head results in True because each member of lis is itself a list. Thanks for any advice!

  • 1
    $\begingroup$ Try Join @@@ TakeList[lis, Length /@ Split[FreeQ[_Integer] /@ lis]] $\endgroup$ – Coolwater May 26 '18 at 6:44
Flatten /@ Split[lis, And/* FreeQ[_Integer]] (* using @Coolwater's idea in a comment*)
SequenceReplace[lis, {a : {Except[_Integer]..}..} :> Join[a]]
SequenceReplace[lis, {a__?(FreeQ[_Integer])} :> Join[a]]
ReplaceRepeated[lis, {a___, b : Repeated[{Except[_Integer] ..}, {2, Infinity}], c___} :> 
  {a, Join[b], c}]

all give

{{a}, {1, 2}, {b}, {3}, {c, z, d, e, f}, {4}}

  • $\begingroup$ Thank you very much for your thoughts. I am going to generalize them for my larger data set, I'll see which suggestion is faster. $\endgroup$ – Suite401 May 26 '18 at 6:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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