4
$\begingroup$

I have a list such as:

a = {1, 2, 4, 3};

and I want to get the 'number' of the list. For this example, I want to get this number: 1243. I do not know how to get it easily. For now, my solution is: a[[1]]*10^3+a[[2]]*10^2+a[[3]]*10^1+a[[4]]; It works. But it is too complex. I want to know a way more convenient.

$\endgroup$

5 Answers 5

5
$\begingroup$
a = {1, 2, 4, 3};
FromDigits[a]

(* 1243 *)
$\endgroup$
4
$\begingroup$

Other than the built-in FromDigits, we can build our wheel

Fold[{10, 1}.{##} &, a]
$\endgroup$
2
  • $\begingroup$ I want to know what is the mean of 'wheel'. Is it a function to achieve something? I know what you express, but I am interest in the meaning of 'wheel'. $\endgroup$
    – user61054
    Commented Dec 8, 2018 at 6:40
  • $\begingroup$ @user61054 Do you want to know what the figurative meaning of "wheel" or how the function Fold works? $\endgroup$ Commented Dec 8, 2018 at 11:28
2
$\begingroup$

Best way would be to use build-in function FromDigits as shown above.

But just in case you'd like a convoluted way to do it, here is another option

a = {1, 2, 4, 3};
ToExpression[StringJoin[ToString[#] & /@ a]]

Mathematica graphics

$\endgroup$
2
$\begingroup$

These are some methods I would not recommend:

lst = {1, 2, 3, 4};

f = (Curry[StringRiffle][""] /* ToExpression);

g = (Through[{
    Identity,
    Length /* Range /* Reverse /* Curry[Plus][-1] /* Curry[Power, 2][10]
}[#]] & /* MapThread[Times] /* Total);

f[lst] (* 1234 *)
g[lst] (* 1234 *)
$\endgroup$
1
  • $\begingroup$ Are you really serious that you would not recommend this? :) $\endgroup$
    – user59583
    Commented Dec 8, 2018 at 12:15
2
$\begingroup$

Here is a method that is faster than FromDigits for the construction of many numbers at once:

a = RandomInteger[{1, 9}, {1000000, 10}];
r1 = FromDigits /@ a; // RepeatedTiming // First
r2 = FromDigits[Transpose[a]]; // RepeatedTiming
r3 = a.(10^Range[9, 0, -1]); // RepeatedTiming // First
r1 == r2 == r3

0.466

0.068

0.040

True

Admittedly, FromDigits[Transpose[a]] is only slower than a.(10^Range[9, 0, -1]) because of Transpose.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.