Is there a map without result in python?

前端 未结 15 1101
北恋
北恋 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:24

    first rewrite the for loop as a generator expression, which does not allocate any memory.

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

    But this expression doesn't actually do anything without finding some way to consume it. So we can rewrite this to yield something determinate, rather than rely on the possibly None result of installWow.

    ( [1, installWow(x,  'installed by me')][0] for x in wowList )
    

    which creates a list, but returns only the constant 1. this can be consumed conveniently with reduce

    reduce(sum, ( [1, installWow(x,  'installed by me')][0] for x in wowList ))
    

    Which conveniently returns the number of items in wowList that were affected.

提交回复
热议问题