Non-lazy evaluation version of map in Python3?

后端 未结 6 1708
醉话见心
醉话见心 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:56

    Using map for its side-effects (eg function call) when you're not interested in returned values is undesirable even in Python2.x. If the function returns None, but repeats a million times - you'd be building a list of a million Nones just to discard it. The correct way is to either use a for-loop and call:

    for row in data:
        writer.writerow(row)
    

    or as the csv module allows, use:

    writer.writerows(data)
    

    If for some reason you really, really wanted to use map, then you can use the consume recipe from itertools and generate a zero length deque, eg:

    from collections import deque
    deque(map(writer.writerow, data), maxlen=0)
    

提交回复
热议问题