7
$\begingroup$

I have some nested lists of symbols, all of the same format, and I wish to convert them to nested lists of integers, i.e.

{e1,{e1,{e1,e2}}} -> {1,{1,{1,2}}}

Any quick ways to do this?

Note: I will always have nested lists of that form, but their length may vary and the symbols may not always have single digit integers in them, e.g.

{e4,{e200,{e1,{e11,e23}}}} -> {4,{200,{1,{11,23}}}}

Many thanks!

$\endgroup$

2 Answers 2

10
$\begingroup$
symbols = {e4, {e200, {e1, {e11, e23}}}};
Map[FromDigits@StringDrop[SymbolName[#], 1] &, symbols, {-1}]

{4, {200, {1, {11, 23}}}}

Map[FromDigits @ StringCases[SymbolName[#], NumberString] &, symbols, {-1}]

{4, {200, {1, {11, 23}}}}

Alternative versions, as suggested by Kuba,

Function[, FromDigits@StringDrop[SymbolName[#], 1], Listable]@symbols
Function[, FromDigits@StringCases[SymbolName[#], NumberString], Listable]@symbols

And, inspired by Jack LaVigne's comment, Replace and ReplaceAll:

Replace[symbols, s_Symbol:>   FromDigits[StringDrop[SymbolName[s], 1]],∞ ]
symbols /. Except[List, s_Symbol] :> FromDigits@StringDrop[SymbolName[s], 1] 

Finally, per J.M.'s comment, a variation on Coolwater's answer with combination of ToExpression and StringDelete:

 ToExpression @ StringDelete[LetterCharacter]@ToString@symbols
$\endgroup$
9
  • 3
    $\begingroup$ Here's an alternative for Map: Function[sym, ..., Listable]. $\endgroup$
    – Kuba
    Sep 29, 2018 at 16:50
  • $\begingroup$ Thank you @Kuba; great suggestion. $\endgroup$
    – kglr
    Sep 29, 2018 at 16:57
  • 1
    $\begingroup$ @kglr Another alternative for Map is to use ReplaceAll. symbols /. e_Symbol /; Not[MatchQ[e, List]] :> FromDigits@StringDrop[SymbolName[e], 1] $\endgroup$ Sep 29, 2018 at 21:33
  • 1
    $\begingroup$ @JackLaVigne fyi ... /. e:Except[List, _Symbol] ... $\endgroup$
    – Kuba
    Sep 29, 2018 at 22:08
  • 1
    $\begingroup$ @DanielWilson-Nunn, without FromDigits or ToExpression wrapping we get {"4", {"200", {"1", {"11", "23"}}}} . $\endgroup$
    – kglr
    Nov 10, 2018 at 21:02
6
$\begingroup$

Alternatively:

symbols = {e4, {e200, {e1, {e11, e23}}}};
ToExpression[StringReplace[ToString[symbols], "e" -> ""]]

{4, {200, {1, {11, 23}}}}

$\endgroup$
1
  • 2
    $\begingroup$ ...or, ToExpression[StringDelete[ToString[symbols], "e"]] $\endgroup$ Sep 29, 2018 at 19:56

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.