Table[ ] Output Cardinality

我只是一个虾纸丫 提交于 2019-12-01 07:12:14

问题


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?


回答1:


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}



回答2:


This should work:

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



回答3:


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.



来源:https://stackoverflow.com/questions/6313505/table-output-cardinality

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