I have a list where the elements are Reals and Integers. How can I extract the Integer? For example, if I have {1, 2, 3.4, 9.9}
, how can I get {1, 2}
?
6 Answers
Try this command
Cases[list, _Integer]
-
$\begingroup$ Thanks.. it runs. But when i erase the
{1}
at the end of the command, it also runs. What is the meaning of{1}
? $\endgroup$– MATIRMAKApr 13, 2013 at 10:53 -
$\begingroup$ To just check on the first level of the list. Actually by default it takes {1} so I better remove it too! $\endgroup$ Apr 13, 2013 at 10:58
Well since we're having fun, I'll like to join the party:
lst = {3, 5.6, 8.19, 2, 5.6, 4, 3, 8.5, 4.137, 7., 1.165}
DeleteCases[lst, _Real]
OR
lst /. x_Real -> Sequence[]
OR
Select[lst, Head[#] == Integer &]
All give:
{3, 2, 4, 3}
-
$\begingroup$ @Mr.Wizard, Thanks, you got my vote too :) $\endgroup$ Apr 14, 2013 at 0:16
-
$\begingroup$ I added a couple more to my answer. I hope you enjoy them. $\endgroup$ Apr 14, 2013 at 0:17
-
$\begingroup$ Why not
Select[lst, IntegerQ]
? $\endgroup$ Apr 14, 2013 at 1:41 -
$\begingroup$ @J.M., that too. Isn't
Head[#]==Integer&
what MMA is doing under the hood when you useIntegerQ
? $\endgroup$ Apr 14, 2013 at 2:42 -
$\begingroup$ I suppose, but I would think
IntegerQ
is idiomatic, while the actual head test is more literal. :) $\endgroup$ Apr 14, 2013 at 2:44
Just for fun, here's a terse method using Pick
:
lst = {3, 5.6, 8.19, 2, 5.6, 4, 3, 8.5, 4.137, 7., 1.165}
Pick[#,#-#,0]& @ lst
{3, 2, 4, 3}
More fun:
Replace[lst, _Real|x_ :> x, 1]
{3, 2, 4, 3}
Only for positive values:
Log@lst ~Level~ {2}
{3, 2, 4, 3}
-
$\begingroup$ Oh wow, that last one using
Log
is clever, wish I could Upvote again. $\endgroup$ Apr 14, 2013 at 0:21
Here's another one, for fun:
lst = {3, 5.6, 8.19, 2, 5.6, 4, 3, 8.5, 4.137, 7., 1.165};
Pick[lst, Mod[lst, 1], 0]
(* {3, 2, 4, 3} *)
if order does not matter:
Attributes[f] = {Orderless};
f[x__Integer, __] := {x}
f @@ {3, 5.6, 8.19, 2, 5.6, 4, 3, 8.5, 4.137, 7., 1.165}
(* {2, 3, 3, 4} *)
Select[lst, Round[#] == #&];
Select[lst, # == Round[#]&];