Now I am working on a python course, but the data in the tasks there is formed as inputs, and not as arguments to the function, as for example in codewars.
To write generators, I have to use input, which cannot be iterated. It turns out this code:
dots = [input() for x in range(int(input()))]
parsedDots = [dot for dot in dots if not '0' in dot]
(This code should make a list where only inputs() without zero coordinate are taken into)
Is it possible, to combine this two generators into one?
Input data example:
4
0 -1
1 2
0 9
-9 -5
You can combine them using the walrus operator, :=
in 3.8+:
parsedDots = [inp for _ in range(int(input())) if '0' not in (inp := input())]
Pre-3.8, the best you can do is convert your original list comprehension (eager, materializes a list
) to a generator expression (lazy), so you don't make an actual list
until after you've filtered out the garbage:
dots = (input() for _ in range(int(input()))) # Parens instead of square brackets makes genexpr
parsedDots = [dot for dot in dots if '0' not in dot]
That has slightly higher overhead than the walrus solution, but no meaningful per-item increase in peak memory usage, and it works on every version of Python since generator expressions were introduced (2.4ish?).