How to format two separate lists in columns, rather than rows in Mathematica?
This seems like it should be a piece of cake, but I haven't found the answer in Mathematica's documentation. Say I have two separate lists, for example x={1,2,3,4,5} and y={1,4,9,16,25}. I want to format these lists as a table with each list as a column, like this:
x y
1 1
2 4
3 9
4 16
5 25
But if I do TableForm[x,y], I get only the first column, like this:
1
2
3
4
5
If I do Grid[{x,y}], I get a table, but formatted as rows instead of columns, 开发者_StackOverflowlike this:
1 2 3 4 5
1 4 9 16 25
Now, if I have my values as {x,y} pairs, rather than separate lists, then I can get almost what I want,like so:
Input: Table[{n,n^2},{n,1,5}]//TableForm
Output:
1 1
2 4
3 9
4 16
5 25
I say almost, because I'd like to have the variable names at the top of each column, and I'd like the columns justified so that the ones digits are always placed vertically in the "ones place", the tens digits in the "tens place", etc.
So, back to my question: If I have two separate lists of the same length, how can I format them as a table of columns? I checked the MMA documentation for Grid and TableForm, but I couldn't find a way to do it. Did I miss something? If there's no direct way to do it, is there a way to transform two separate lists into pairs of values that could then be formatted in columns using TableForm?
Thanks for any suggestions you might have.
Personally I prefer Grid to TableForm. Maybe something like this?
Some preliminaries:
x = {1, 2, 3, 4, 5};
y = {1, 4, 9, 16, 25};
grid = Transpose@{x, y};
headings = {{Item["x", Frame -> {True, True}],
Item["y", Frame -> {True, False}]}};
The following code,
Grid[Join[headings, grid], Alignment -> Right, Dividers -> All,
Spacings -> {3, 1}, FrameStyle -> Orange]
gives this as output, for example:
Often in Mathematica, you use Transpose to switch the role of row and column.
In[6]:= x = {1,2,3,4,5}; y = {1,4,9,16,25};
In[7]:= {x,y} // Transpose // TableForm
Out[7]//TableForm= 1 1
2 4
3 9
4 16
5 25
Instead of using Transpose
you can use the option TableDirection
:
x={1,2,3,4,5};y={1,4,9,16,25};
TableForm[{x,y},TableDirections->Row,TableHeadings->{{"x","y"}}]
Grid[Transpose[{x, y}], Alignment -> Right]
I would use:
x = {1, 2, 3, 4, 5};
y = {1, 4, 9, 16, 25};
TableForm[{{x, y}}, TableAlignments -> Right]
Here are some more convoluted examples, demonstrating the way TableForm works. It does get complicated, and I usually have to experiment a bit to get what I want.
a = {1, 2, 3};
b = {4, 5, 6};
{a, b} // TableForm
{{a}, {b}} // TableForm
{{{a}}, {{b}}} // TableForm
{{{a}, {b}}} // TableForm
{{List /@ a, List /@ b}} // TableForm
{{a}, b} // TableForm
{{{a}, b}} // TableForm
{{{a}}, {b}} // TableForm
{{{{a}}, {b}}} // TableForm
精彩评论