Count how many values in a list that satisfy certain condition
I take compactness, you mentioned in the question, as shorter code. So, I present
sum(float(num) >= 1.3 for num in mylist)
This takes advantage of the fact that, in python True
values are taken as 1 and False
as 0. So, whenever float(num) >= 1.3
evaluates to Truthy, it will be 1
and if it fails, result would be 0. So, we add all the values together to get the total number of items which are greater than or equal to 1.3
.
You can check that like this
True == 1
# True
True + True
# 2
False * 10
# 0
Get the first item from an iterable that matches a condition
Python 2.6+ and Python 3:
If you want StopIteration
to be raised if no matching element is found:
next(x for x in the_iterable if x > 3)
If you want default_value
(e.g. None
) to be returned instead:
next((x for x in the_iterable if x > 3), default_value)
Note that you need an extra pair of parentheses around the generator expression in this case − they are needed whenever the generator expression isn't the only argument.
I see most answers resolutely ignore the next
built-in and so I assume that for some mysterious reason they're 100% focused on versions 2.5 and older -- without mentioning the Python-version issue (but then I don't see that mention in the answers that do mention the next
built-in, which is why I thought it necessary to provide an answer myself -- at least the "correct version" issue gets on record this way;-).
Python <= 2.5
The .next()
method of iterators immediately raises StopIteration
if the iterator immediately finishes -- i.e., for your use case, if no item in the iterable satisfies the condition. If you don't care (i.e., you know there must be at least one satisfactory item) then just use .next()
(best on a genexp, line for the next
built-in in Python 2.6 and better).
If you do care, wrapping things in a function as you had first indicated in your Q seems best, and while the function implementation you proposed is just fine, you could alternatively use itertools
, a for...: break
loop, or a genexp, or a try/except StopIteration
as the function's body, as various answers suggested. There's not much added value in any of these alternatives so I'd go for the starkly-simple version you first proposed.
How do I check the list elements satisfy a given condition?
Maybe something like this? Make function that will be called for list and return True if list satisfies condition and False if it doesn't.
def some_function(nums):
for i in range(len(nums) - 1):
y = nums[i] + nums[i + 1]
z = y ** 0.5
#till here found the square root of the sum of the adjacent numbers in list
if z.is_integer() not True:
# if there is some two numbers that don't meet condition, function will return False
return False
return True
You call it like this: meet_condition = some_function(x)
After that just check if it's True and if it is print list and appropriate text.
How do I get the number of elements in a list (length of a list) in Python?
The len()
function can be used with several different types in Python - both built-in types and library types. For example:
>>> len([1, 2, 3])
3
Replacing list elements that satisfy some condition with items from another list in Python
you can do like this.
list1=[0,1,6,4,2,8]
list2=[10,20,30,40]
j=0
ans=[0]*len(list1)
for i in range(len(list1)):
if list1[i] <= 4:
ans[list1.index(list1[i])]+=list2[j]
if(j<len(list2)):
j+=1
else:
ans[i]+=list1[i]
print(ans)
that should work.
How to check if all elements of a list match a condition?
The best answer here is to use all()
, which is the builtin for this situation. We combine this with a generator expression to produce the result you want cleanly and efficiently. For example:
>>> items = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
True
>>> items = [[1, 2, 0], [1, 2, 1], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
False
Note that all(flag == 0 for (_, _, flag) in items)
is directly equivalent to all(item[2] == 0 for item in items)
, it's just a little nicer to read in this case.
And, for the filter example, a list comprehension (of course, you could use a generator expression where appropriate):
>>> [x for x in items if x[2] == 0]
[[1, 2, 0], [1, 2, 0]]
If you want to check at least one element is 0, the better option is to use any()
which is more readable:
>>> any(flag == 0 for (_, _, flag) in items)
True
Related Topics
How to Create an Object and Add Attributes to It
Serving Dynamically Generated Zip Archives in Django
Real World Example About How to Use Property Feature in Python
Could Not Find a Version That Satisfies the Requirement <Package>
Nameerror: Global Name 'Xrange' Is Not Defined in Python 3
Remove or Replace Spaces in Column Names
Generalise Slicing Operation in a Numpy Array
How to Get Md5 Sum of a String Using Python
How to Share Numpy Random State of a Parent Process with Child Processes
How Does Python's Comma Operator Work During Assignment
How to Understand the Output of Dis.Dis
Python Read File as Stream from Hdfs
Numpy to Tfrecords: Is There a More Simple Way to Handle Batch Inputs from Tfrecords
Merging a List of Time-Range Tuples That Have Overlapping Time-Ranges
Crawling with an Authenticated Session in Scrapy
Gunicorn Autoreload on Source Change
How to Force a Python Wheel to Be Platform Specific When Building It
How to Correctly Parse Utf-8 Encoded HTML to Unicode Strings with Beautifulsoup