Table[ ] Output Cardinality

南楼画角 提交于 2019-12-01 08:04:30

A simple example:

Table[Sequence @@ ConstantArray[1, i - 1], {i, 2}]
Out[1] = {1}

This need not always return a list with smaller cardinality. For e.g., {i,3} returns equal and {i,4} returns more.

Or an even sillier example would be

Table[Sequence @@ {}, {i, 2}]

but I don't know if it counts.


You could also use Piecewise inside Table

Table[Sequence @@ Piecewise[{
    {ConstantArray[1, i], i < 3},
    {ConstantArray[2, i], 3 <= i < 5},
    {{}, i >= 5}}],
 {i, 20}]

Out[2] = {1, 1, 1, 2, 2, 2, 2, 2, 2, 2}

This should work:

Table[Sequence @@ {}, {i, 10}]

Assuming that I now understand your intent, I do not see the advantage to "on the fly" elimination within Table itself. One could accomplish it with something like:

Table[If[EvenQ@i, i, ##&[]], {i, 25}]

but it is faster to use Join:

Join @@ Table[If[EvenQ@i, {i}, {}], {i, 25}]

or DeleteCases:

DeleteCases[Table[If[EvenQ@i, i], {i, 25}], , 1]

and in this simple case, Select is more than twice as fast:

Table[i, {i, 25}] ~Select~ EvenQ

If it is a matter of memory usage, the first method using Sequence does come out ahead, but the Join method is not far behind.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!