-5
$\begingroup$

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}?

$\endgroup$
0

6 Answers 6

7
$\begingroup$

Try this command

Cases[list, _Integer]
$\endgroup$
2
  • $\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$
    – MATIRMAK
    Apr 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$
    – Spawn1701D
    Apr 13, 2013 at 10:58
5
$\begingroup$

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}
$\endgroup$
7
  • $\begingroup$ @Mr.Wizard, Thanks, you got my vote too :) $\endgroup$
    – RunnyKine
    Apr 14, 2013 at 0:16
  • $\begingroup$ I added a couple more to my answer. I hope you enjoy them. $\endgroup$
    – Mr.Wizard
    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 use IntegerQ? $\endgroup$
    – RunnyKine
    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
2
$\begingroup$

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}
$\endgroup$
1
  • $\begingroup$ Oh wow, that last one using Log is clever, wish I could Upvote again. $\endgroup$
    – RunnyKine
    Apr 14, 2013 at 0:21
1
$\begingroup$

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} *)
$\endgroup$
2
  • $\begingroup$ ...or SawtoothWave[lst]. $\endgroup$ Apr 14, 2013 at 14:10
  • $\begingroup$ .. or Gamma[lst] - (lst - 1)! :D $\endgroup$
    – rm -rf
    Apr 14, 2013 at 14:12
0
$\begingroup$

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} *)
$\endgroup$
0
$\begingroup$
Select[lst, Round[#] == #&];
Select[lst, # == Round[#]&];
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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