Durai Sankaran
Durai Sankaran

Reputation: 43

Nested for loop in Single Line

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

Answers (1)

TerryA
TerryA

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

Related Questions