TransWikia.com

How to make a table from two lists?

Mathematica Asked by user2895279 on June 22, 2021

I have two lists.

list1 = {115.366, 103.583, 115.24, 91.4648, 93.1291, 485.744, 427.888,489.401, 403.942}

list2 = {114.062, 105.17, 114.857, 91.6497, 93.2112, 398.588, 458.713,410.015, 380.659}

I want these lists to form a table that looks like this.

115.366    114.062
103.583    105.17
115.24     114.857
and so on

5 Answers

Transpose[{list1, list2}] // TableForm

$begin{array}{cc} 115.366 & 114.062 103.583 & 105.17 115.24 & 114.857 91.4648 & 91.6497 93.1291 & 93.2112 485.744 & 398.588 427.888 & 458.713 489.401 & 410.015 403.942 & 380.659 end{array}$

Correct answer by David G. Stork on June 22, 2021

Although solution has been already accepted, here is another way it could be done

Example

Code

Row[(Column[#, Frame -> True] & /@ {list1, list2})]

Note: list1 and list2 as in OP

Output

output example

Reference

Map
Row
Column

Answered by e.doroskevic on June 22, 2021

And then there is Grid:

transposedData = Transpose @ { list1, list2 }; (* make a list of tuples *)

Grid[
  transposedData,
  (* options for further formatting go here *)
]

Table

Just to give an idea of what is possible using options for Grid:

Grid[
  transposedData,
  Frame -> {All, None, {{3, 2} -> Directive[Red, Thick]}},
  Alignment -> {Decimal, Decimal}
]

nicer table

Answered by gwr on June 22, 2021

Make your own function:

In[1]= myThread[l1__, l2__] := If[Length[l1] != Length[l2],"Error in length", {l1[[#]], l2[[#]]} & /@ Range[1, Length[l1]]]

list1 = Reverse[Range[1, 9]]
Out[1]= {9, 8, 7, 6, 5, 4, 3, 2, 1}

list1 = Range[1, 9]
Out[2]= {1, 2, 3, 4, 5, 6, 7, 8, 9}

In[2]= myThread[list1__, list2__]
Out[3]= {{9, 1}, {8, 2}, {7, 3}, {6, 4}, {5, 5}, {4, 6}, {3, 7}, {2, 8}, {1,9}} 

You can expand the logic to any dimension. Also, applying //Tableform function at the end will format the output in the form you seek, viz.:

In[262]= list//TableForm
Out[263]//TableForm=
1    9
2    8
etc... 

Answered by Ole SkoolNO on June 22, 2021

Thanks to the @cvgmt's feedback, alternatives to Transpose:

Code 1

Thread[{list1, list2}]

% == Transpose[{list1, list2}]
(* Out: True *)

Code 2

Can only be used on two lists, each of them should be 1-dimensional:

Inner[List, list1, list2, List]

% == Transpose[{list1, list2}]
(* Out: True *)

Speed Comparison

lg[n_] := ConstantArray[RandomReal[{-1, 1}, 10^n], 2]

thread[{l1_, l2_}] := Thread[{l1, l2}];
inner[{l1_, l2_}] := Inner[List, l1, l2, List];
transpose[{l1_, l2_}] := Transpose[{l1, l2}];

Needs["GeneralUtilities`"]
BenchmarkPlot[{thread, inner, transpose}, lg, TimeConstrained -> 20]

Result:

enter image description here

Answered by Ben Izd on June 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP