1

Absolute beginner question here. I have two lists in mathematica. The first one was generated by the Table command:

Table[QP[[i]], {i, 10}] which generates the list:

{52.5, 45., 37.5, 30., 22.5, 15., 7.5, 0., -7.5, -15.}

the second is a Range

Range[0, 9, 1]

which generates {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

I need to get these into a list of lists. i.e. {{0,52.5},{1,45} ... } etc. But I can't seem to get it. Do you need to use loops? Because I think that what I want can be generated with the Table and Array commands.

Thanks

Dr. belisarius
  • 60,527
  • 15
  • 115
  • 190
franklin
  • 1,800
  • 7
  • 32
  • 59
  • 3
    Please remember to use lowercase letters as the first char in user defined symbols. You will save yourself a lot of headaches – Dr. belisarius Sep 15 '11 at 21:01
  • 1
    The answers to [this](http://stackoverflow.com/q/5370848/499167) question *Pair lists to get tuples in order* may also be of interest. – 681234 Sep 16 '11 at 00:56

4 Answers4

7

Transpose may be what you want:

list1 = {52.5, 45., 37.5, 30., 22.5, 15., 7.5, 0., -7.5, -15.}

list2 = Range[0, 9, 1]
Transpose[{list2, list1}]

gives

{{0, 52.5}, {1, 45.}, {2, 37.5}, {3, 30.}, {4, 22.5}, {5, 15.}, {6, 7.5}, {7, 0.}, {8, -7.5}, {9, -15.}}

681234
  • 4,214
  • 2
  • 35
  • 42
  • 2
    Reviewing the answers and comparing with [here](http://stackoverflow.com/q/5370848/499167), I notice that only `Flatten` has been omitted (which also allow a Transpose of a 'ragged' array). This is easy to forget! See [here](http://stackoverflow.com/questions/5370848/pair-lists-to-create-tuples-in-order/5372194#5372194). `Flatten[{list2, list1}, {{2}}] == Transpose[{list2, list1}]` – 681234 Sep 16 '11 at 01:03
5

The first parameter of Table can be any expression. You can have it output a list of lists, by specifying a list as the first parameter:

Table[{i-1, QP[[i]]}, {i, 10}]
(* {{0, QP[[1]]}, {1, QP[[2]]}, ... {8, QP[[9]]}, {9, QP[[10]]}} *)
Mike Bailey
  • 12,479
  • 14
  • 66
  • 123
Jonathan
  • 1,487
  • 11
  • 12
5
Thread[List[Range[0, 9], QP[[;; 10]]]]
Dr. belisarius
  • 60,527
  • 15
  • 115
  • 190
4

To complete the exposition of methods, you could use MapIndexed

MapIndexed[{First[#2] - 1,#1}&, data]

where

data = {52.5, 45., 37.5, 30., 22.5, 15., 7.5, 0., -7.5, -15.}

Or, you could use MapThread

MapThread[List, {Range[0,9], data}]

Although, MapIndexed is more appropriate since it does not require you to generate an extra list.

A last point I want to make is that your code Table[QP[[i]], {i, 10}] implies that QP itself is a list. (The double brackets, [[ ]], gave it away.) If that is correct, than Table isn't the best way to generate a subset, you can use Part ([[ ]]) along with Span directly

QP[[ 1 ;; 10 ]]

or

QP[[ ;; 10 ]]

Then, you can replace data in the first bits of code with either of those forms.

rcollyer
  • 10,475
  • 4
  • 48
  • 75