4
$\begingroup$

I have the list

\[ScriptCapitalD] = 
  {824, 1082, 1135, 1308, 1359, 1372, 1401, 1412, 1601, 
   1638, 1641, 1674, 1709, 1805, 1947, 2208}

I would like to extract a sublist according to certain defined conditions, such as extracting only values which lie in the range 1000-1500.

What is the best way to do this?

$\endgroup$
  • $\begingroup$ Select[\[ScriptCapitalD], 1000 <= # <= 1500 &] would do it. But there are many faster ways that already have answers somewhere here... $\endgroup$ – aardvark2012 Dec 2 '17 at 11:25
  • $\begingroup$ Possible duplicate here $\endgroup$ – aardvark2012 Dec 2 '17 at 11:34
6
$\begingroup$

The standard Mathematica function for that kind of selection, is Select.

data = 
  {824, 1082, 1135, 1308, 1359, 1372, 1401, 1412, 1601, 1638, 1641, 1674, 1709, 
   1805, 1947, 2208};
Select[data, Between[#, {1000, 1500}] &]

{1082, 1135, 1308, 1359, 1372, 1401, 1412}

Update

Between has an operator form, so

Select[data, Between[{1000, 1500}]]

will work and is nicer.

Select has its operator form, too, so one can also write

Select[Between[{1000, 1500}]] @ data
$\endgroup$
  • $\begingroup$ Can you explain what the operator & does in the argument of Select? $\endgroup$ – Physkid Dec 2 '17 at 11:38
  • $\begingroup$ @Physkid When writing &, everything to the left of it becomes the body of a function. E.g with plus = # + #2 & then plus[2, 3] evaluates to 5 $\endgroup$ – Coolwater Dec 2 '17 at 11:43
  • $\begingroup$ @Physkid. Look up Function in the documentation. $\endgroup$ – m_goldberg Dec 2 '17 at 11:44
  • $\begingroup$ @m_goldberg I like your updated code-cleaner $\endgroup$ – Physkid Dec 3 '17 at 9:33
4
$\begingroup$
sdt = Select[dt, 1000 <= # <= 1500 &]

{1082, 1135, 1308, 1359, 1372, 1401, 1412}
$\endgroup$
1
$\begingroup$
Cases[Clip[lst, {1000, 1500}, {0, 0}], Except[0]]

{1082, 1135, 1308, 1359, 1372, 1401, 1412}

Alternatives, based on Clip:

lst // Pick[#, Clip[#, {1000, 1500}, {0, 0}] // Unitize, 1] &
Clip[lst, {1000, 1500}, {0, 0}] /. 0 -> Nothing
$\endgroup$
0
$\begingroup$

If you selection criteria is always a window (Between[{a,b}]), sorting the data and then doing a binary search may be more efficient. See Windowed binary search

$\endgroup$

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