Python方式循环进行纯粹基于副作用的理解 [英] Pythonic way to cycle through purely side-effect-based comprehension

查看:74
本文介绍了Python方式循环进行纯粹基于副作用的理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行完整的生成器理解的最Python方式是什么,而您不关心返回值,而是这些操作完全基于副作用?

What is the most pythonic way to execute a full generator comprehension where you don't care about the return values and instead the operations are purely side-effect-based?

一个示例是根据谓词值拆分列表,如这里.考虑编写生成器理解是很自然的

An example would be splitting a list based on a predicate value as discussed here. It's natural to think of writing a generator comprehension

split_me = [0, 1, 2, None, 3, '']
a, b = [], []
gen_comp = (a.append(v) if v else b.append(v) for v in split_me)

在这种情况下,我能想到的最佳解决方案是使用any

In this case the best solution I can come up with is to use any

any(gen_comp)

但是,对于那些没有看到这种模式的人来说,发生的事情并不立即显而易见.有没有更好的方法可以在不将所有返回值保存在内存中的情况下循环进行完整的理解?

However that's not immediately obvious what's happening for someone who hasn't seen this pattern. Is there a better way to cycle through that full comprehension without holding all the return values in memory?

推荐答案

您可以通过不使用生成器表达式来实现.

只需编写一个适当的循环:

Just write a proper loop:

for v in split_me:
    if v:
        a.append(v)
    else:
        b.append(v)

或者也许:

for v in split_me:
    target = a if v else b
    target.append(v)

如果您要立即立即执行生成器,则在此处使用生成器表达式毫无意义.当您只想将值附加到另外两个列表中时,为什么还要生成一个对象并加上一个None返回值序列?

Using a generator expression here is pointless if you are going to execute the generator immediately anyway. Why produce an object plus a sequence of None return values when all you wanted was to append values to two other lists?

使用显式循环既可以让代码的未来维护者(包括您)更容易理解,也可以提高效率.

Using an explicit loop is both more comprehensible for future maintainers of the code (including you) and more efficient.

这篇关于Python方式循环进行纯粹基于副作用的理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆