发电机中的迭代输入()
现在,我正在研究Python课程,但是该任务中的数据是作为输入形成的,而不是作为功能的参数,例如在CodeWars中。
要编写生成器,我必须使用输入,这无法迭代。事实证明,此代码:(
dots = [input() for x in range(int(input()))]
parsedDots = [dot for dot in dots if not '0' in dot]
此代码应在只有零坐标的情况下列出一个列表)
是否有可能将这两个生成器组合到一个?
输入数据示例:
4
0 -1
1 2
0 9
-9 -5
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 Walrus Operator,:= < < /a>在3.8+中:3.8
pre-3.8,您能做的最好的就是将您的原始列表理解(急切地,将
list
>)转换为发电机表达式(Lazy),因此您不会制作实际的list
,直到您过滤掉垃圾后:略 的开销比Walrus解决方案高,但是峰值内存使用情况没有有意义的人均增加,并且自引入发电机表达式以来(2.4ish?),它在每种版本的Python上都起作用。
You can combine them using the walrus operator,
:=
in 3.8+: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 actuallist
until after you've filtered out the garbage: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?).