问题
I have a very large table of data something like:
lista = {{2,8},{3,4},{5,2}..}
I would like to add x to every element so it would be
lista ={{x,2,8},{x,3,4},{x,5,2}.....}
This seems to me like it should be rather trivial but I have not been able to find a solution.
I would appreciate any help.
回答1:
This is very nearly a duplicate of Appending to the rows of a table and an exact duplicate of Prepend 0 to sublists on the dedicated site where your question should have been asked. Many more methods, with timings, are provided in those threads but here are two good methods to start with:
lista = {{2, 8}, {3, 4}, {5, 2}};
ArrayPad[lista, {{0, 0}, {1, 0}}]
{{0, 2, 8}, {0, 3, 4}, {0, 5, 2}}
Or:
ArrayFlatten @ {{0, lista}}
{{0, 2, 8}, {0, 3, 4}, {0, 5, 2}}
Dedicated StackExchange site:
回答2:
Join
can be useful here:
Map[Join[{x}, #] &, {{2, 8}, {3, 4}, {5, 2}}]
回答3:
So I have two methods for doing this; both of them work fine, but I think the latter is better for technical reasons; although I have not tested their performance:
First Method:
lista = RandomInteger[{0, 10}, {10, 2}]
(*{{1, 3}, {0, 3}, {5, 5}, {4, 2}, {1, 7}, {3, 6}, {2, 2}, {3, 1}, {7, 6}, {8, 10}}*)
For[i = 1, i <= Length[lista], i++, PrependTo[lista[[i]], x]]
lista
(*{{x, 1, 3}, {x, 0, 3}, {x, 5, 5}, {x, 4, 2}, {x, 1, 7}, {x, 3, 6}, {x, 2, 2}, {x, 3, 1}, {x, 7, 6}, {x, 8, 10}}*)
Second Method:
lista = RandomInteger[{0, 10}, {10, 2}]
(*{{0, 5}, {6, 0}, {4, 6}, {3, 2}, {8, 1}, {4, 9}, {0, 5}, {9, 10}, {3,0}, {8, 4}}*)
X = ConstantArray[x, Length[lista]];
lista = Transpose[Prepend[Transpose[lista], X]]
(*{{x, 0, 5}, {x, 6, 0}, {x, 4, 6}, {x, 3, 2}, {x, 8, 1}, {x, 4, 9}, {x,0, 5}, {x, 9,10}, {x, 3, 0}, {x, 8, 4}}*)
来源:https://stackoverflow.com/questions/18370117/adding-a-third-column-of-data-in-mathematica