I have a list of strings:

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

I would like to use StringJoin on the last elements where initial elements are the same to obtain:

res = {{"a","b","xzw"},{"d","e","y"},{"d","c","x"}}


lis = SortBy[lis, {#[[1]]} &]
SequenceCases[lis, {{a_, b_, c_}, {a_, b_, d_}} :> {a, b, StringJoin[c, d]}]

only gives:

{{"a", "b", "wx"}}

Thanks for any suggestions.

  • $\begingroup$ At least closely related: mathematica.stackexchange.com/q/26574/5478 $\endgroup$ – Kuba Sep 27 '18 at 19:04
  • $\begingroup$ @Suite401, do you have control on how the "initials" are generated? If they where integers (which can be achieved with ToCharacterCode), then I could also image faster methods. $\endgroup$ – Henrik Schumacher Sep 27 '18 at 19:43
  • $\begingroup$ @Henrik, Each actual element of the list looks like: {DateObject,String,String representation of integer,String,String representation of integer,String,String,String} so I'm not sure there's much to be done, but am interested in your thoughts. $\endgroup$ – Suite401 Sep 27 '18 at 19:53
  • $\begingroup$ Okay, my idea would have required that the number of keys is known a priorily. Btw., I found out that Carl Woll's code is much faster than mine. $\endgroup$ – Henrik Schumacher Sep 27 '18 at 19:58

Another variation:

KeyValueMap[Append] @ GroupBy[lis, Most->Last, StringJoin]

{{"a", "b", "xzw"}, {"d", "e", "y"}, {"d", "c", "x"}}

although you may like just the output of GroupBy[lis, Most->Last, StringJoin] better.

 {key, value} \[Function] Join[key, {StringJoin[value]}],
 GroupBy[lis, Part[#, 1 ;; 2] & -> Last]

{{"a", "b", "xzw"}, {"d", "e", "y"}, {"d", "c", "x"}}

  • $\begingroup$ That's probably the first time I've seen anyone use the infix function notation here. I forgot that even existed. $\endgroup$ – Sjoerd Smit Sep 27 '18 at 20:18
  • $\begingroup$ @Sjoerd Actually, I use it quite often... $\endgroup$ – Henrik Schumacher Sep 27 '18 at 20:19

Another one:

 KeyValueMap[Append] @ Merge[StringJoin][ {#, #2} -> #3 & @@@ lis ]
  • $\begingroup$ Thanks Henrik, Kuba; am checking to see which is faster on big data set $\endgroup$ – Suite401 Sep 27 '18 at 19:06

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.