Is there a map without result in python?

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

    You could make your own "each" function:

    
    def each(fn, items):
        for item in items:
            fn(item)
    
    
    # called thus
    each(lambda x: installWow(x, 'installed by me'), wowList)
    
    

    Basically it's just map, but without the results being returned. By using a function you'll ensure that the "item" variable doesn't leak into the current scope.

    0 讨论(0)
  • 2020-12-03 05:18

    How about this?

    for x in wowList:
        installWow(x, 'installed by me')
    del x
    
    0 讨论(0)
  • 2020-12-03 05:23

    Every expression evaluates to something, so you always get a result, whichever way you do it. And any such returned object (just like your list) will get thrown away afterwards because there's no reference to it anymore.

    To clarify: Very few things in python are statements that don't return anything. Even a function call like

    doSomething()
    

    still returns a value, even if it gets discarded right away. There is no such thing as Pascal's function / procedure distinction in python.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 05:26

    I can not resist myself to post it as separate answer

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

    only twist is installWow should return itself e.g.

    def installWow(*args):
        print args
        return installWow
    
    0 讨论(0)
  • 2020-12-03 05:27

    Just make installWow return None or make the last statement be pass like so:

    
    def installWow(item, phrase='installed by me'):
      print phrase
      pass
    

    and use this:

    
    list(x for x in wowList if installWow(x))
    

    x won't be set in the global name space and the list returned is [] a singleton

    0 讨论(0)
提交回复
热议问题