发电机中的迭代输入()

发布于 2025-02-12 23:31:07 字数 345 浏览 1 评论 0原文

现在,我正在研究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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柳若烟 2025-02-19 23:31:07

您可以使用 Walrus Operator,:= < < /a>在3.8+中:3.8

parsedDots = [inp for _ in range(int(input())) if '0' not in (inp := input())]

pre-3.8,您能做的最好的就是将您的原始列表理解(急切地,将list>)转换为发电机表达式(Lazy),因此您不会制作实际的list,直到您过滤掉垃圾后:

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]

的开销比Walrus解决方案高,但是峰值内存使用情况没有有意义的人均增加,并且自引入发电机表达式以来(2.4ish?),它在每种版本的Python上都起作用。

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?).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文