I would like to understand how this is unpacked line by line, assuming it is possible. I hope this pseudocode is acceptable.
for item in (i for item in item if condition)
Many thanks!
CodePudding user response:
for i in items:
if condition:
for j in item:
So for this, it does the if statement each time the for loop goes through an iteration, and then it does the second for loop if that condition is fulfilled. Otherwise, the first for loop just iterates without doing anything.
From what I can tell, that's what the pseudocode is trying to say, but the way I have it above would be the correct Python syntax.
CodePudding user response:
This is (item for item in items if condition)
generator and can apply for
on each element:
items = [1,0,1,0,0,1]
for j in (item for item in items if item):
print(j)
Unpacked of above code can be:
def fnd_con(items):
for item in items:
if item:
yield item
items = [1,0,1,0,0,1]
res = fnd_con(items)
for j in res:
print(j)
Output:
1
1
1