13
$\begingroup$

how easily can I convert elements of this list to string. If I have output like this:

{{M, 1, 0, 0, 1, 1, 1, 0}, {A, 0, 0, 0}}

And I want something like this:

{{M, 1001110}, {A, 000}}

Or

{{M, "1001110"}, {A, "000"}}
$\endgroup$

4 Answers 4

10
$\begingroup$
lis = {{M, 1, 0, 0, 1, 1, 1, 0}, {A, 0, 0, 0}};
{First@#, StringJoin[ToString /@ Rest@#]} & /@ lis

(* {{M, "1001110"}, {A, "000"}} *)
$\endgroup$
2
  • 3
    $\begingroup$ Similarly, {#1, StringJoin @@ ToString /@ {##2}} & @@@ lis. $\endgroup$
    – march
    Apr 5, 2016 at 21:38
  • $\begingroup$ @march. That's a good one too. $\endgroup$
    – RunnyKine
    Apr 5, 2016 at 22:02
8
$\begingroup$
Cases[{{M, 1, 0, 0, 1, 1, 1, 0}, {A, 0, 0, 0}}, {x_, y__} :> {x, 
   StringJoin[ToString /@ {y}]}]
$\endgroup$
2
  • $\begingroup$ Why RuleDelayed required? (It is, I know; but why?) For example, if the second pattern mapped to just {y}, it would not be required. $\endgroup$
    – Alan
    Apr 5, 2016 at 21:01
  • $\begingroup$ @Alan I assume to keep y from being shadowed by another variable named y $\endgroup$
    – Daniel
    Apr 5, 2016 at 22:12
3
$\begingroup$
Transpose[{a[[;; , 1]], StringJoin @@@ IntegerString @ a[[;; , 2 ;;]]}]
$\endgroup$
3
$\begingroup$

If on the off chance you are seeking binary output for numbers then:

dat = {{M, 1, 0, 0, 1, 1, 1, 0}, {A, 0, 0, 0}};
{First@#, BaseForm[FromDigits[Rest@#, 2], 2]} & /@ dat

enter image description here

Hope this helps.

$\endgroup$

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.