Non-lazy evaluation version of map in Python3?

后端 未结 6 1722
醉话见心
醉话见心 2020-12-07 00:23

I\'m trying to use map in Python3. Here\'s some code I\'m using:

import csv

data = [
    [1],
    [2],
    [3]
]

with open(\"output.csv\", \"w         


        
6条回答
  •  春和景丽
    2020-12-07 00:58

    I would use a function to extract data from the iterable using something like this:

    def rake(what, where=None):
        for i in what: 
            if where: where.append(i)
    
    rake(map(writer.writerow, data))
    

    If you know up front that you won't ever be collecting the output of the mapped function then you could simplify that to just:

    for i in what: pass
    

    But neither approach keeps excess data around unless you supply a list to put it in. And this approach should work equally well with map, filter, reduce, generators, range, and anything else that you could pass in to the rake function that for can iterate over.

提交回复
热议问题