python中是否有没有结果的地图?

2022-01-24 00:00:00 python iteration

问题描述

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

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


解决方案

你可以使用内置的any函数将一个函数不带return语句应用于任意项由生成器返回而不创建列表.可以这样实现:

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)

我发现这是您想要实现的最简洁的习惯用法.

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

在内部,installWow 函数确实返回 None,它在逻辑操作中的计算结果为 False.any 基本上将 or 归约操作应用于生成器返回的所有项目,当然都是 None,所以它必须遍历所有生成器返回的项目.最后它确实返回 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 的情况下才有效,例如 None 或 0.如果它返回的结果为 True 在某些时候,例如 1,它不会应用于迭代器中的任何剩余元素.为了安全起见,这个习惯用法主要用于没有返回语句的函数.

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.

相关文章