问题
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
回答1:
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]]}} *)
回答2:
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.}}
回答3:
Thread[List[Range[0, 9], QP[[;; 10]]]]
回答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.
来源:https://stackoverflow.com/questions/7437144/using-nested-arrays-and-lists-in-mathematica