Is there a map without result in python?

前端 未结 15 1118
北恋
北恋 2020-12-03 04:33

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

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

Sometime

15条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 05:17

    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.

    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.

    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.

提交回复
热议问题