Here’s a really simple question regarding pythonic coding.
Given a list, if you want to calculate the proportion of items satisfying (A and B), out of those satisfying (A), a natural solution would be:
Imagine the list is of integers, condition A is (>3), condition B is (>5)
count = 0
correct = 0
for item in items:
if item > 3:
count += 1
if item > 5:
correct += 1
score = float(correct) / count
print '%.2f' % score
An alternative solution:
count = len([1 for i in items if i > 3])
correct = len([1 for i in items if i > 5])
score = float(correct) / count
print '%.2f' % score
The alternative looks sexier to me, though it loops through items twice and is not efficient. Is there an accepted pythonic solution to this common scenario or is the first solution good enough?
Thanks.
Your (alternate) solution is great, except for this small change:
The syntax that looks like a list comprehension without the brackets is called a generator expression.
I’m not aware of any readable way to get a solution without iterating over the list twice, other than the one you already have. I’d still go with the solution above, unless a profiler tells me I have to speed this up.