Python Forum

Full Version: List comprehension. Shor for loop version
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,
I have read about list comprehensions
and I was wondering if my simple for loop below can be reduced to a list comprehension in python:

The loop only checks if the initial list has an entry of a specific value and if yes it increases a counter

zero_guess=max(classes_samples[idx]) # get the more frequent class 
zero_precision=0
for i in (y_true[idx]):
    if (i==zero_guess):
        zero_precision=zero_precision+1
Thanks a lot
Alex
If you are after zero_precision count then it's better to use generator expression instead of list comprehension (you don't need elements, you need end result) You can take advantage that boolean is subclass of integers and True and False are 1 and 0 respectively.

Assuming that your for loop is working one can rewrite it as:

zero_precision = sum(i==zero_guess for i in y_true[idx])