4

I am using two For loops. When the inner loop finishes, I don't want to print but I want to store the result from the inner loop in some variable so that I can call that variable in the future. That result will come in the form of a list.

For example, in the 1st iteration,it is returning some value, e.g. {2,4}. in the 2nd iteration,it is returning {3,4}.

But I don't want to print them every time. I want some variable to store {{2,4},{3,4}}. How to do that?

Here I am retrieving all the data except Null.

tab={{{"option1", "option3", "option4", "optio", "Null", 
        "Null"}, {"option2", "option5", "option6", "option7", "Null", "Null"}, 
         {"option", "op", "Null", "Null", "Null", "Null"}}};

For[j = 1, j <= Length[tab[[1]]], j++,
  For[i = 1, i <= Length[Rest[tab[[1, j]]]], i++,

If[TrueQ[(Rest[tab[[1, j]]][[i]]) == "Null"], count++, count = 0]]
 Print[
Table[Rest[tab[[1, j]]][[i]], {i,1, (Length[Rest[tab[[1, j]]]] - count), 1}]] ]
Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323
Jennifer
  • 953
  • 4
  • 16

2 Answers2

4

In light of your update, is this all you're trying to do?

Cases[#, Except@"Null"] & /@ tab[[1, All, 2 ;;]]

{{"option3", "option4", "optio"}, {"option5", "option6", "option7"}, {"op"}}

Specific references to understand this code for your convenience:
Part, Function, Slot, Map, Cases, Except


If for some reason you feel you must use For loops, you can substitute Sow and Reap for Print as follows:

Reap[
  For[j = 1, j <= Length[tab[[1]]], j++,
   For[i = 1, i <= Length[Rest[tab[[1, j]]]], i++,
    If[TrueQ[(Rest[tab[[1, j]]][[i]]) == "Null"], count++, count = 0]
   ];
   Sow @ Table[
     Rest[tab[[1, j]]][[i]], {i, 
      1, (Length[Rest[tab[[1, j]]]] - count), 1}]
  ]
][[2, 1]]

{{"option3", "option4", "optio"}, {"option5", "option6", "option7"}, {"op"}}

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
3

A version using Select, Map ( shortform /@ ) and lambda functions ( # and & ).

Select[Rest@#, # =!= "Null" &] & /@ First@tab

{{"option3", "option4", "optio"}, {"option5", "option6", "option7"}, {"op"}}

I wasn't sure if tab was intended to have an apparently redundant layer of nesting, as in {{{...},{...},{..}}}, if it wasn't you can drop the extra braces and remove First from the code.

Did you also want to ignore the first element of each sublist of tab as per Mr Wizards answer? If not, then you can drop Rest from the code given.

image_doctor
  • 10,234
  • 23
  • 40