Let L
be a list of several lists. And the length of each list is less than 1000.
You can create L by
L = Table[ConstantArray[1, RandomInteger[999]], 100000];
For example, let L
looks like
{a list whose length is 340,
a list whose length is 525,
a list whose length is 829,
a list whose length is 422,
......}
What I want to get is a list of integers
M = {3, 5, 8, 4,......}
That is, if the length of an element is
between 0~99, assign 0,
between 100~199, assign 1,
...
between 900~999, assign 9.
In fact this can be done easily by Floor[Length[#]/100]&/@L
But I want to achieve it by built-in Replace
.
Here is the code I did my best :
Replace[L, Table[_?(Length[#] < 100 k &) -> k - 1 /. k -> a, {a, 1, 10}], {1}] (*code of an interest*)
But there is one thing I don't like about this code algorithmically.
This code computes Length[#]
too often.
(Length
is very fast, so just lucky this time.
What if the function is so slow.)
I want the Length
to be computed only once for each element.
I tried codes like :
Replace[L, Module[{Leng}, Leng = Hold[Length[#]];
Table[_?(Leng < 100 k &) -> T[k] /. k -> a, {a, 10}]], {1}] (*failed code*)
I tried Module,Block,With
... all failed. Can you help me?
By modifying *code of an interest* slightly, can you show a code that computes Length
only once for each element?
Quotient[Length@#, 100] & /@ L
. I would post that as the answer except that you seem to really want Replace. $\endgroup$