在python中有没有结果的地图? [英] Is there a map without result in python?

查看:87
本文介绍了在python中有没有结果的地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,我只是想为一个条目列表执行一个函数 - 例如:

Sometimes, I just want to execute a function for a list of entries -- eg.:

for x in wowList:
   installWow(x, 'installed by me')

有时我需要这些东西模块初始化,所以我不希望在全局命名空间中有像x这样的足迹。一种解决方案是将map与lambda一起使用:

Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:

map(lambda x: installWow(x, 'installed by me'), wowList)

但这当然会创建一个很好的列表[None,None,...]所以我的问题是,如果有一个没有返回列表的类似函数 - 因为我只是不需要它。

But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.

(当然我也可以使用_x因此不会留下可见的足迹 - 但地图解决方案看起来很整洁......)

(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)

推荐答案

你可以使用内置的-in 任何函数将函数不带返回语句应用于生成器返回的任何项而不创建列表。这可以这样实现:

You can use the built-in any function to apply a function without return statement to any item returned by a generator without creating a list. This can be achieved like this:

any(installWow(x, 'installed by me') for x in wowList)

我发现这是你想要达到的最简洁的idom。

I found this the most concise idom for what you want to achieve.

在内部, installWow 函数确实返回,其结果为 False逻辑运算中的任何基本上对生成器返回的所有项目应用缩减操作,这些都是没有当然,所以它必须迭代生成器返回的所有项目。最后它确实返回 False ,但这不需要打扰你。好处是:没有列表被创建为副作用。

Internally, the installWow function does return None which evaluates to False in logical operations. any basically applies an or reduction operation to all items returned by the generator, which are all None of course, so it has to iterate over all items returned by the generator. In the end it does return False, but that doesn't need to bother you. The good thing is: no list is created as a side-effect.

请注意,只有当函数返回的值为 False ,例如或0.如果确实返回的值为 True 在某些时候,例如 1 ,它将不会应用于迭代器中的任何其余元素。为了安全起见,主要用于没有return语句的函数。

Note that this only works as long as your function returns something that evaluates to False, e.g., None or 0. If it does return something that evaluates to True at some point, e.g., 1, it will not be applied to any of the remaining elements in your iterator. To be safe, use this idiom mainly for functions without return statement.

这篇关于在python中有没有结果的地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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