0

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

rafaelc
  • 57,686
  • 15
  • 58
  • 82
  • Can you provide the full nested structure? – What Apr 26 '18 at 12:10
  • this is my nested structure, In condition I have dataframe column data – Durai Sankaran Apr 26 '18 at 12:11
  • 1. What purpose would you have for putting a nested loop in a single line? Just curiosity? 2. This is difficult to answer when all of your conditions and variables are `...`. 3. You probably want a list comprehension inside a list comprehension. – Garrett Gutierrez Apr 26 '18 at 12:12
  • Possible duplicate of [List comprehension on a nested list?](https://stackoverflow.com/questions/18072759/list-comprehension-on-a-nested-list) – hoefling Apr 26 '18 at 19:50

1 Answers1

3

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)
TerryA
  • 58,805
  • 11
  • 114
  • 143