I have a list created in Python, something like a=[1.0,3.7,1.0,3.9]
.
I need to check a condition with if
at least two values in the list have values in the range [3.0,4.0], then do something.
Asked
Active
Viewed 2,180 times
-1
1 Answers
4
if sum(1 for e in a if 3.0 <= e < 4.0) >= 2:
something()
1 for e in a if 3.0 <= e < 4.0
will return the iterator (1, 1)
(i.e. a value 1
for each e
such that it is between 3.0
and 4.0
); then summing those ones gets us the count of the elements that satisfies the condition.
will this early exit when the list
a
is very long?
No. This will, tho, but it makes the logic a bit more complex:
from itertools import accumulate
if any(n for n in accumulate(1 for e in a if 3.0 <= e < 4.0) if n >= 2):
something()

Amadan
- 191,408
- 23
- 240
- 301
-
Wow, I didn't know you could do a boolean range change like `min <= e < max`. Awesome! Is this Python3.*? – jhuang Dec 08 '17 at 06:08
-
2No, it's both Python2 and Python3. However, do not try to generalise it to other languages, most don't have that bit of syntactic sugar. – Amadan Dec 08 '17 at 06:10
-
2@jhuang: [Python2](https://docs.python.org/3.5/reference/expressions.html#comparisons), [Python3](https://docs.python.org/2.7/reference/expressions.html#comparisons): "Comparisons can be chained arbitrarily, e.g., `x < y <= z` is equivalent to `x < y and y <= z`, except that `y` is evaluated only once (but in both cases `z` is not evaluated at all when `x < y` is found to be false)." – Amadan Dec 08 '17 at 06:16
-
@Amadan will this early exit when the list `a` is very long? – user1767754 Dec 08 '17 at 06:43