Find next lower value in list of (float) numbers?
<p>How should I write the <code>find_nearest_lower</code> function?</p>

<pre><code>&gt;&gt;&gt; values = [10.1, 10.11, 10.20]
&gt;&gt;&gt; my_value = 10.12
&gt;&gt;&gt; nearest_lower = find_nearest_lower(values, my_value)
&gt;&gt;&gt; nearest_lower
10.11
</code></pre>

<p>This needs to work in Python 2.6 without access to numpy.</p>

<pre><code>&gt;&gt;&gt; def find_nearest_lower(seq, x):
...     return max(item for item in seq if item &lt; x)
...
&gt;&gt;&gt; values = [10.1, 10.11, 10.20]
&gt;&gt;&gt; my_value = 10.12
&gt;&gt;&gt; nearest_lower = find_nearest_lower(values, my_value)
&gt;&gt;&gt; nearest_lower
10.11
</code></pre>

<p>This approach will raise an exception if there aren't any values in <code>seq</code> that are smaller than <code>x</code>. If this is undesirable behavior, you could instead return a sentinel value, such as None:</p>

<pre><code>def find_nearest_lower(seq, x):
    candidates = [item for item in seq if item &lt; x]
    if not candidates: return None
    return max(candidates)
</code></pre>

<p>Or</p>

<pre><code>def find_nearest_lower(seq, x):
    try:
        return max(item for item in seq if item &lt; x)
    except ValueError:
        return None
</code></pre>

<p>... If you're more of an "ask forgiveness" person than a "look before you leap" person.</p>

python python-2.6