Reputation: 43
I have a logic need to count the iteration
counts = []
for .. in ..:
count = 0
for .. in ..:
if ..:
count +=1
counts.append(count)
How to change this logic into single line loop in python
Upvotes: 0
Views: 693
Reputation: 59974
Use sum()
with nested list comprehensions:
counts = [sum([1 for c in b if p(c)]) for b in a]
This is equivalent to:
counts = []
for b in a:
count = 0
for c in b:
if p(c):
count = count + 1
counts.append(count)
Upvotes: 3