5
$\begingroup$

I have the following list which I am importing from Pyhton - thus the format:

l = {{"a", "[1,2,3,4,5]"}, {"b", "[6,7,8,9,10]"}}

I wonder how can I covert this to the following shape:

{{{"a"}, {1,2,3,4,5}}, {{"b"}, {6,7,8,9,10}}}

Essentially for each letter the numbers in front should be converted to integer and list so one can do operations on them.

$\endgroup$
  • 1
    $\begingroup$ Can you export Python results to a more standard format? $\endgroup$ – Kuba Jul 17 at 11:06
  • $\begingroup$ How does the Python file looks like in plain text? $\endgroup$ – rhermans Jul 17 at 11:46
  • 1
    $\begingroup$ Thanks for accepting Coolwater's answer, it's a very good answer, but anyhow I think you were too hasty doing that. While accepting is one of the things to do after your question is answered, we recommend that users should test answers before voting and wait 24 hours before accepting the best one. Even more in this case where there were unresolved questions in the comments. $\endgroup$ – rhermans Jul 17 at 13:07
4
$\begingroup$

One way:

Replace[l, s_String :> If[StringMatchQ[s, "[" ~~ ___ ~~ "]"],
   ToExpression["{" <> StringTake[s, {2, -2}] <> "}"], {s}], {2}]
$\endgroup$
4
$\begingroup$
l /. 
  s_String :> StringReplace[s, "[" ~~ st___ ~~ "]" :> ToExpression["{" <> st <> "}"]] /. 
  StringExpression -> Identity /. 
  s_String :> {s}

{{{"a"}, {1, 2, 3, 4, 5}}, {{"b"}, {6, 7, 8, 9, 10}}}

Also

l1 = l;
l1[[All, 1]] = Map[List]@l[[All, 1]];
l1[[All, 2]] = Map[ToExpression@StringJoin["List", #] &]@l[[All, 2]];
l1

{{{"a"}, {1, 2, 3, 4, 5}}, {{"b"}, {6, 7, 8, 9, 10}}}

l2 = StringReplace[#, {"[" -> "{", "]" -> "}"}] & /@ l;
l2[[All, 1]] = List /@ l2[[All, 1]];
l2[[All, 2]] = ToExpression[l2[[All, 2]]];
l2

{{{"a"}, {1, 2, 3, 4, 5}}, {{"b"}, {6, 7, 8, 9, 10}}}

l3 = MapAt[List, l, {All, 1}];
l3 = MapAt[ToExpression@StringReplace[#, {"[" -> "{", "]" -> "}"}] &, l3, {All, 2}];
l3

{{{"a"}, {1, 2, 3, 4, 5}}, {{"b"}, {6, 7, 8, 9, 10}}}

$\endgroup$
4
$\begingroup$
{{#1}, ToExpression@StringSplit[#2,"["|"]"|","]}&@@@l

alternatively, using regex:

{{#1}, ToExpression@StringSplit[#2,RegularExpression["\W{1}"]]}&@@@l

{{{a}, {1, 2, 3, 4, 5}}, {{b}, {6, 7, 8, 9, 10}}}

$\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.