Table[ ] Output Cardinality

2019-02-19 01:35发布

The Table[ ] command usually returns a list with the same cardinality of its iterator.

Table[i, {i,4}] 
(*
->{1,2,3,4}
*)

It is easy to show that is possible to return a list with a greater cardinality than the iterator

Table[Sequence @@ ConstantArray[1, i], {i, 2}]
(*
->{1,1,1}
*)

But ... Are there ways to return a list with LESS cardinality than the iterator?

3条回答
叛逆
2楼-- · 2019-02-19 01:55

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.

查看更多
走好不送
3楼-- · 2019-02-19 01:58

This should work:

Table[Sequence @@ {}, {i, 10}]
查看更多
老娘就宠你
4楼-- · 2019-02-19 01:59

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}
查看更多
登录 后发表回答